okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
ad33b8074
main
1// src/kernels/s_gemv_parity.cpp - P2.S2's parity test for the S-family GEMV. 2// 3// Four source types, chosen to cover every branch the kernel has: 4// 5// S2 Q2_0 2-bit, bias -1, group 64 affine 6// S4 Q4_0 4-bit, bias -8, group 32 affine 7// S4 IQ4_NL 4-bit, bias 0, group 32 CODEBOOK (non-linear, no bias can express it) 8// S8 Q8_0 8-bit, bias -128, group 32 affine 9// 10// That is all three template instantiations, both codebooks, and four different biases. The offset branch 11// (`has_offset`, only Q4_K and Q5_K) is NOT exercised here and the test prints that fact rather than leaving a 12// green result to imply otherwise - Q4_K's canonicalisation needs the packed 6-bit scale/min pairs, and the 13// honest move is to say so than to half-build it. 14// 15// THE REFERENCE IS THE CHAIN: for each type the CPU side reconstructs the RAW GGUF block from the canonical 16// planes and decodes it with that type's scalar dequantizer from include/strata/artifact/dequant.hpp - the 17// ones `bench/micro/dequant_xcheck` checks against **ggml's own** dequantizers. Reconstructing raw from 18// canonical is the inverse of what the packer does, and it is written here independently of the packer so the 19// two are not the same code. 20#define DPCT_PROFILING_ENABLED 21#include <sycl/sycl.hpp> 22#include <dpct/dpct.hpp> 23#include "strata/artifact/dequant.hpp" 24#include "strata/kernels/s_gemv.hpp" 25 26#include <cmath> 27#include <cstdint> 28#include <cstdio> 29#include <cstring> 30#include <algorithm> 31#include <chrono> 32#include <random> 33#include <string> 34#include <vector> 35 36namespace { 37 38void check (dpct::err0 e ,const char * what ) { 39} 40 41// Finite, exactly representable fp16 patterns WITH full mantissas. Not powers of two: with only powers of 42// two every product is exact and the comparison cannot round, which is how the first version of s2_gemv's test 43// managed a worst error of exactly zero without proving anything. 44const uint16_t kScales []= {0x3E00 ,0x3555 ,0x3C01 ,0x4248 ,0x4123 ,0x2AAA ,0x4A2B ,0x3800 , 450xBE00 ,0xB555 ,0xC248 ,0x2AAB ,0x4A2C ,0x2AAB ,0xB800 }; 46 47struct Case { 48const char * name ; 49 strata::kernels::SForm form ; 50int raw_bytes ;// one block 51// Reconstruct the raw GGUF block for one group from the canonical codes/scales, and return the number of 52// elements the block decodes to (which may exceed group_elems: Q8_0's block IS one group, Q2_0's too). 53int (* to_raw )(const uint8_t * codes ,size_t code_off ,const uint16_t * scale_bits ,size_t scale_off ,uint8_t * raw ); 54double (* dequant )(const uint8_t * raw ,float * out ); 55}; 56 57// ---- Q2_0: raw = { fp16 d ; uint8 qs[16] }, 64 elements, code i at byte i/4 bits (i%4)*2 - identical to the 58// canonical plane, so this is a straight copy plus the scale. 59int q2_0_to_raw (const uint8_t * codes ,size_t co ,const uint16_t * scale_bits ,size_t so ,uint8_t * raw ) { 60const uint16_t d = scale_bits [so ]; 61raw [0 ]= (uint8_t ) (d & 0xFF ); 62raw [1 ]= (uint8_t ) (d >>8 ); 63// `codes` is one code PER ELEMENT (64 of them); a Q2_0 block stores them PACKED, 4 per byte, element i at 64// byte i/4 bits (i%4)*2. The two coincide as a byte layout only if you confuse them, which is exactly the 65// mistake the first version of this function made by copying 16 bytes verbatim. 66for (int b = 0 ;b < 16 ;++ b ) { 67raw [2 + b ]= (uint8_t ) ((codes [co + 4 * b + 0 ]& 3 ) | ((codes [co + 4 * b + 1 ]& 3 ) <<2 ) | 68 ((codes [co + 4 * b + 2 ]& 3 ) <<4 ) | ((codes [co + 4 * b + 3 ]& 3 ) <<6 )); 69 } 70return 64 ; 71} 72double q2_0_deq (const uint8_t * raw ,float * out ) { 73 strata::dequantize_q2_0 (raw ,out ); 74return 64 ; 75} 76 77// ---- Q4_0: raw = { fp16 d ; uint8 qs[16] }, 32 elements; element j is the LOW nibble of byte j and element 78// j+16 the HIGH nibble. The canonical plane stores one code per element, so this re-packs them. 79int q4_0_to_raw (const uint8_t * codes ,size_t co ,const uint16_t * scale_bits ,size_t so ,uint8_t * raw ) { 80const uint16_t d = scale_bits [so ]; 81raw [0 ]= (uint8_t ) (d & 0xFF ); 82raw [1 ]= (uint8_t ) (d >>8 ); 83for (int j = 0 ;j < 16 ;++ j )raw [2 + j ]= (uint8_t ) ((codes [co + j ]& 0x0F ) | (codes [co + 16 + j ] <<4 )); 84return 32 ; 85} 86double q4_0_deq (const uint8_t * raw ,float * out ) { 87 strata::dequantize_q4_0 (raw ,out ); 88return 32 ; 89} 90 91// ---- IQ4_NL: identical packing to Q4_0, different decode (a table, not a bias). 92int iq4_to_raw (const uint8_t * codes ,size_t co ,const uint16_t * scale_bits ,size_t so ,uint8_t * raw ) { 93return q4_0_to_raw (codes ,co ,scale_bits ,so ,raw ); 94} 95double iq4_deq (const uint8_t * raw ,float * out ) { 96 strata::dequantize_iq4_nl (raw ,out ); 97return 32 ; 98} 99 100// ---- Q8_0: raw = { fp16 d ; int8 qs[32] }, 32 elements. The canonical code plane is UNSIGNED with bias 101// -128 (round 154's fix), so the raw int8 byte is exactly the canonical code reinterpreted - a straight copy, 102// which is why this type is the cheapest one to check and the one whose sign bug was found by the pack. 103int q8_0_to_raw (const uint8_t * codes ,size_t co ,const uint16_t * scale_bits ,size_t so ,uint8_t * raw ) { 104const uint16_t d = scale_bits [so ]; 105raw [0 ]= (uint8_t ) (d & 0xFF ); 106raw [1 ]= (uint8_t ) (d >>8 ); 107// NOT a straight copy. The canonical code plane is UNSIGNED with bias -128, so canonical code c means the 108// value (c - 128); the raw block stores that as an `int8_t`, whose reinterpretation as an unsigned byte is 109// `c ^ 0x80` - a SIGN-BIT FLIP, not the identity. Assuming identity is the same family of mistake as the 110// round-154 Q8_0 bug that the pack found, and it is why this reconstruction is written out rather than 111// memcpy'd. 112for (int j = 0 ;j < 32 ;++ j )raw [2 + j ]= (uint8_t ) (codes [co + j ] ^0x80 ); 113return 32 ; 114} 115double q8_0_deq (const uint8_t * raw ,float * out ) { 116 strata::dequantize_q8_0 (raw ,out ); 117return 32 ; 118} 119 120// ---- S4/Q4_K: the ONLY canonical form with an offset, and the only one whose scale is an FP32 PRODUCT 121// (`fl(d*sc)`) rather than a widened fp16. Both facts make it the case worth having. 122// 123// There is no `to_raw` for it in the table above because its canonical planes are DERIVED from the raw 124// parameters, not the other way round: the packer computes `scale = d*sc` and `offset = -(dmin*m)`, so this 125// generates d, dmin and the eight (sc, m) pairs, derives the planes exactly as the packer does, and writes a 126// raw block from the SAME parameters. Inverting those products instead would be ambiguous. 127void test_q4k (long long n_in ,long long n_out ,double tol ,int * total_bad ) { 128using strata::kernels::Codebook ; 129using strata::kernels::SForm ; 130const SForm form {4 ,0 ,32 ,Codebook ::Affine , true}; 131 132 std::mt19937 rng (777 ); 133const int n_scales = (int ) (sizeof (kScales ) /sizeof (kScales [0 ])); 134const long long n_groups = n_in /32 ; 135const long long codes_per_row = n_in /2 ; 136 137 std::vector < uint16_t > x ((size_t )n_in ); 138for (long long i = 0 ;i < n_in ;++ i )x [(size_t )i ]= kScales [rng () %n_scales ]; 139 140 std::vector < uint8_t > codes_el ((size_t )n_out * n_in ); 141for (size_t i = 0 ;i < codes_el .size ();++ i )codes_el [i ]= (uint8_t ) (rng ()& 0x0F ); 142 std::vector < uint8_t > codes ((size_t )n_out * codes_per_row ,0 ); 143for (size_t i = 0 ;i < codes_el .size ();++ i ) { 144const size_t o = i / (size_t )n_in ,k = i % (size_t )n_in ; 145codes [o * (size_t )codes_per_row + k /2 ] |= (uint8_t ) (codes_el [i ] << ((k %2 )* 4 )); 146 } 147 std::vector < float > scales ((size_t )n_out * n_groups ),offsets ((size_t )n_out * n_groups ); 148 149struct Row { 150uint16_t d ,dmin ; 151uint8_t sc [8 ],m [8 ]; 152 }; 153 std::vector < Row > rows ((size_t )n_out ); 154for (long long o = 0 ;o < n_out ;++ o ) { 155Row & r = rows [(size_t )o ]; 156r .d = kScales [rng () %n_scales ]; 157r .dmin = kScales [rng () %n_scales ]; 158for (int g = 0 ;g < 8 ;++ g ) { 159r .sc [g ]= (uint8_t ) (rng ()& 0x3F ); 160r .m [g ]= (uint8_t ) (rng ()& 0x3F ); 161for (long long sb = 0 ;sb < n_in /256 ;++ sb ) { 162scales [(size_t ) (o * n_groups + sb * 8 + g )]= strata::fp16_to_fp32 (r .d )* (float )r .sc [g ]; 163offsets [(size_t ) (o * n_groups + sb * 8 + g )]= - (strata::fp16_to_fp32 (r .dmin )* (float )r .m [g ]); 164 } 165 } 166 } 167 168 std::vector < float > ref ((size_t )n_out ,0.0f ); 169 std::vector < double > cond ((size_t )n_out ,0.0 ); 170double worst_plane_ref = 0.0 ;// max |planes - raw block| over every element, on the CPU alone 171 std::vector < uint8_t > blk (144 ); 172 std::vector < float > dec (256 ); 173// A Q4_K raw block covers 256 elements, so a 2560-element row is TEN superblocks, each with its own 174// 144-byte block. The first version of this loop ran `step < 4` - one superblock, 256 of the row's 2560 175// elements - while the kernel accumulated all of them, and the resulting 29x relative error was the 176// reference being short, not the kernel being wrong. 177for (long long o = 0 ;o < n_out ;++ o ) { 178const Row & r = rows [(size_t )o ]; 179float acc = 0.0f ; 180double sum_abs = 0.0 ;// the natural scale of this row's dot product (see the metric below) 181double plane_ref_diff = 0.0 ;// (a) vs (b): planes against the raw block, both on the CPU 182for (long long sb = 0 ;sb < n_in /256 ;++ sb ) { 183// ONE 144-byte block per 256-element SUPERBLOCK, with all four steps' qs bytes filled BEFORE the 184// decode. The previous version decoded a fresh block per STEP and then read all 256 elements 185// from each, so three quarters of every decode came from zeroed qs - four decodes of a 186// quarter-filled block per superblock, which is the whole of the 1.17e4 disagreement. 187// `scripts/probe_q4k_groups.cpp` builds it this way and agrees exactly, group by group. 188blk .assign (144 ,0 ); 189blk [0 ]= (uint8_t ) (r .d & 0xFF ); 190blk [1 ]= (uint8_t ) (r .d >>8 ); 191blk [2 ]= (uint8_t ) (r .dmin & 0xFF ); 192blk [3 ]= (uint8_t ) (r .dmin >>8 ); 193for (int j = 0 ;j < 4 ;++ j ) {// the exact inverse of get_scale_min_k4 194blk [4 + j ]= (uint8_t ) ((r .sc [j ]& 0x3F ) | ((r .sc [j + 4 ] >>4 ) <<6 )); 195blk [8 + j ]= (uint8_t ) ((r .m [j ]& 0x3F ) | ((r .m [j + 4 ] >>4 ) <<6 )); 196blk [12 + j ]= (uint8_t ) ((r .sc [j + 4 ]& 0x0F ) | ((r .m [j + 4 ]& 0x0F ) <<4 )); 197 } 198for (int step = 0 ;step < 4 ;++ step ) { 199for (int l = 0 ;l < 32 ;++ l ) {// elements 0..31 LOW nibbles, 32..63 HIGH 200const long long e0 = o * n_in + sb * 256 + step * 64 + l ; 201const long long e1 = e0 + 32 ; 202blk [16 + step * 32 + l ]= 203 (uint8_t ) ((codes_el [(size_t )e0 ]& 0x0F ) | (codes_el [(size_t )e1 ] <<4 )); 204 } 205 } 206 strata::dequantize_q4_K (blk .data (),dec .data ()); 207for (int j = 0 ;j < 256 ;++ j ) { 208const float term = dec [(size_t )j ]* strata::fp16_to_fp32 (x [(size_t ) (sb * 256 + j )]); 209acc += term ; 210sum_abs += std::fabs ((double )term );// the CONDITION of this dot product 211 212// THE THIRD DECODE. (a) the raw block through the scalar dequantizer, (b) the canonical 213// PLANES through `code*scale + offset`, (c) the GPU. If (a) != (b) then this test built 214// planes that disagree with its own raw block and the kernel is innocent; if (a) == (b) and 215// (c) differs, the kernel is wrong. Without (b) there is no way to tell which. 216const long long elem = sb * 256 + j ; 217const long long g = elem /32 ; 218const int code = (int )codes_el [(size_t ) (o * n_in + elem )]; 219const float b_dec = (float )code * scales [(size_t ) (o * n_groups + g )]+ 220offsets [(size_t ) (o * n_groups + g )]; 221if (std::fabs ((double ) (b_dec - dec [(size_t )j ]))> plane_ref_diff ) { 222plane_ref_diff = std::fabs ((double ) (b_dec - dec [(size_t )j ])); 223 } 224 } 225 } 226ref [(size_t )o ]= acc ; 227cond [(size_t )o ]= sum_abs ; 228if (!(plane_ref_diff <=worst_plane_ref ))worst_plane_ref = plane_ref_diff ; 229 } 230 231uint16_t * d_x = nullptr ; 232uint8_t * d_codes = nullptr ; 233float * d_scales = nullptr ,* d_offsets = nullptr ,* d_y = nullptr ; 234check (DPCT_CHECK_ERROR (d_x = sycl::malloc_device < uint16_t > ( 235x .size (), dpct::get_in_order_queue ())), 236"cudaMalloc x" ); 237check (DPCT_CHECK_ERROR (d_codes = (uint8_t * )sycl::malloc_device ( 238codes .size (), dpct::get_in_order_queue ())), 239"cudaMalloc codes" ); 240check (DPCT_CHECK_ERROR (d_scales = sycl::malloc_device < float > ( 241scales .size (), dpct::get_in_order_queue ())), 242"cudaMalloc scales" ); 243check (DPCT_CHECK_ERROR (d_offsets = sycl::malloc_device < float > ( 244offsets .size (), dpct::get_in_order_queue ())), 245"cudaMalloc offsets" ); 246check (DPCT_CHECK_ERROR (d_y = sycl::malloc_device < float > ( 247 (size_t )n_out , dpct::get_in_order_queue ())), 248"cudaMalloc y" ); 249/* 250DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming 251in the original code the source host memory is pageable memory. If the 252memory is not pageable, call wait() on event return by memcpy API to ensure 253synchronization behavior. 254*/ 255check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy ( 256d_x ,x .data (),x .size ()* sizeof (uint16_t )).wait ()), 257"copy x" ); 258/* 259DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming 260in the original code the source host memory is pageable memory. If the 261memory is not pageable, call wait() on event return by memcpy API to ensure 262synchronization behavior. 263*/ 264check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy ( 265d_codes ,codes .data (),codes .size ()).wait ()), 266"copy codes" ); 267/* 268DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming 269in the original code the source host memory is pageable memory. If the 270memory is not pageable, call wait() on event return by memcpy API to ensure 271synchronization behavior. 272*/ 273check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy ( 274d_scales ,scales .data (),scales .size ()* sizeof (float )).wait ()), 275"copy scales" ); 276/* 277DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming 278in the original code the source host memory is pageable memory. If the 279memory is not pageable, call wait() on event return by memcpy API to ensure 280synchronization behavior. 281*/ 282check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy ( 283d_offsets ,offsets .data (),offsets .size ()* sizeof (float )).wait ()), 284"copy offsets" ); 285 strata::kernels::s_gemv (d_x ,d_codes ,d_scales ,d_offsets ,d_y ,n_in ,n_out ,form ); 286 std::vector < float > got ((size_t )n_out ); 287check (DPCT_CHECK_ERROR ( 288 (dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()) 289 .memcpy (got .data (),d_y ,got .size ()* sizeof (float )) 290 .wait ()), 291"copy back" ); 292 293// THE ERROR IS MEASURED AGAINST sum|term|, NOT AGAINST THE RESULT. A dot product of 2560 signed terms 294// cancels, so `|ref-got| / |ref|` is a statement about the condition number, not about the kernel: a row 295// whose terms are ~1e7 and whose result is ~1e3 reports a relative error of 50 for an absolute error of 296// 1e-6 of the terms. `sum_abs` is the natural scale of the computation, and comparing to it is what 297// makes a tolerance mean "agrees to within rounding" instead of "did not cancel". 298long long bad = 0 ; 299double worst = 0.0 ,worst_res = 0.0 ; 300for (long long o = 0 ;o < n_out ;++ o ) { 301const double a = ref [(size_t )o ],b = got [(size_t )o ]; 302const double scale = cond [(size_t )o ]> 1e-30 ?cond [(size_t )o ] :1e-30 ; 303const double rel = std::fabs (a - b ) /scale ; 304const double rel_res = std::fabs (a - b ) / (std::fabs (a )> 1e-30 ? std::fabs (a ) :1e-30 ); 305if (!(rel <=worst ))worst = rel ; 306if (!(rel_res <=worst_res ))worst_res = rel_res ; 307if (!(rel <=tol ))++ bad ; 308 } 309double lo = ref [0 ],hi = ref [0 ]; 310for (float v :ref ) { 311lo = std::fmin (lo ,v ); 312hi = std::fmax (hi ,v ); 313 } 314 std::printf (" %-10s %lld rows, %lld over tol, worst rel-to-terms %.3e (rel-to-result %.3e)\n" , 315"S4/Q4_K" ,n_out ,bad ,worst ,worst_res ); 316 std::printf (" ref spread [%.4g, %.4g], condition (sum|term|) up to %.4g\n" ,lo ,hi , 317* std::max_element (cond .begin (),cond .end ())); 318 std::printf (" CPU planes vs CPU raw block: max |diff| = %.3e -> %s\n" ,worst_plane_ref , 319worst_plane_ref == 0.0 320 ?"the test is SELF-CONSISTENT" 321 :"*** THE TEST DISAGREES WITH ITSELF - fix the reference before believing any GPU result ***" ); 322if (hi - lo <=0.0 ) { 323 std::fprintf (stderr ,"VACUOUS: S4/Q4_K reference is constant\n" ); 324 std::exit (1 ); 325 } 326* total_bad += (int )bad ; 327 sycl::free (d_x , dpct::get_in_order_queue ()); 328 sycl::free (d_codes , dpct::get_in_order_queue ()); 329 sycl::free (d_scales , dpct::get_in_order_queue ()); 330 sycl::free (d_offsets , dpct::get_in_order_queue ()); 331 sycl::free (d_y , dpct::get_in_order_queue ()); 332} 333 334}// namespace 335 336 337// ------------------------------------------------------------------ benchmark 338// 339// P2.S10 wants a first measurement and a ledger entry, and the objective is stated in tokens per second, so 340// the useful output is not GiB/s but "milliseconds of expert matvec per token". Warm-up runs are discarded 341// (the first launch pays module load and page faults) and the MINIMUM is reported alongside the mean, because 342// the minimum is the one not polluted by another process on the machine. 343void bench_s2_gemv (long long n_in ,long long n_out ,int iters ,int * split_bad ) { 344using strata::kernels::Codebook ; 345using strata::kernels::SForm ; 346const SForm form {2 ,-1 ,64 ,Codebook ::Affine , false}; 347const long long n_groups = n_in /64 ; 348const long long codes_per_row = n_in /4 ; 349 350 std::vector < uint8_t > codes ((size_t )n_out * codes_per_row ,0xA5 ); 351 std::vector < float > scales ((size_t )n_out * n_groups ,0.001f ); 352 std::vector < uint16_t > x ((size_t )n_in ,0x3C00 );// 1.0 in fp16 353 354uint16_t * d_x = nullptr ; 355uint8_t * d_codes = nullptr ; 356float * d_scales = nullptr ,* d_y = nullptr ; 357check (DPCT_CHECK_ERROR (d_x = sycl::malloc_device < uint16_t > ( 358x .size (), dpct::get_in_order_queue ())), 359"bench x" ); 360check (DPCT_CHECK_ERROR (d_codes = (uint8_t * )sycl::malloc_device ( 361codes .size (), dpct::get_in_order_queue ())), 362"bench codes" ); 363check (DPCT_CHECK_ERROR (d_scales = sycl::malloc_device < float > ( 364scales .size (), dpct::get_in_order_queue ())), 365"bench scales" ); 366check (DPCT_CHECK_ERROR (d_y = sycl::malloc_device < float > ( 367 (size_t )n_out , dpct::get_in_order_queue ())), 368"bench y" ); 369/* 370DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming 371in the original code the source host memory is pageable memory. If the 372memory is not pageable, call wait() on event return by memcpy API to ensure 373synchronization behavior. 374*/ 375check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy ( 376d_x ,x .data (),x .size ()* sizeof (uint16_t )).wait ()), 377"bench copy x" ); 378/* 379DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming 380in the original code the source host memory is pageable memory. If the 381memory is not pageable, call wait() on event return by memcpy API to ensure 382synchronization behavior. 383*/ 384check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy ( 385d_codes ,codes .data (),codes .size ()).wait ()), 386"bench copy codes" ); 387/* 388DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming 389in the original code the source host memory is pageable memory. If the 390memory is not pageable, call wait() on event return by memcpy API to ensure 391synchronization behavior. 392*/ 393check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy ( 394d_scales ,scales .data (),scales .size ()* sizeof (float )).wait ()), 395"bench copy scales" ); 396 397for (int i = 0 ;i < 3 ;++ i ) strata::kernels::s_gemv (d_x ,d_codes ,d_scales ,nullptr ,d_y ,n_in ,n_out ,form ); 398 399 std::vector < double > ms ; 400for (int i = 0 ;i < iters ;++ i ) { 401const auto t0 = std::chrono::steady_clock::now (); 402 strata::kernels::s_gemv (d_x ,d_codes ,d_scales ,nullptr ,d_y ,n_in ,n_out ,form ); 403const auto t1 = std::chrono::steady_clock::now (); 404ms .push_back (std::chrono::duration < double , std::milli > (t1 - t0 ).count ()); 405 } 406 std::sort (ms .begin (),ms .end ()); 407double mean = 0 ; 408for (double v :ms )mean += v ; 409mean /= (double )ms .size (); 410 411const double weights = (double )n_in * (double )n_out ; 412const double bytes = (double )n_out * (double )codes_per_row + (double )n_out * n_groups * 4.0 ; 413 std::printf ("s2_gemv bench [%lld x %lld] %d iters\n" ,n_in ,n_out ,iters ); 414 std::printf (" ms per gemv: min %.4f median %.4f mean %.4f\n" ,ms .front (),ms [ms .size () /2 ],mean ); 415 std::printf (" min -> %.1f G weights/s, %.1f GiB/s of S2 streamed\n" ,weights /ms .front () /1e6 , 416bytes / (1024.0 * 1024 * 1024 ) / (ms .front () /1000.0 )); 417 418// The projection the objective is stated against: 48 layers x 10 experts x 3 roles, all of one token's 419// experts, at the measured per-role rate. This is the VRAM-resident path only - the CPU expert path and 420// the KV/attention work are separate and are NOT included. 421const double roles_per_token = 48.0 * 10.0 * 3.0 ; 422const double tok_ms = roles_per_token * ms .front (); 423 std::printf (" per token: %.0f roles x %.4f ms = %.1f ms -> %.1f tok/s (expert matvec only)\n" , 424roles_per_token ,ms .front (),tok_ms ,tok_ms > 0 ?1000.0 /tok_ms :0.0 ); 425 std::printf (" NOTE: expert matvec ONLY. No attention, no KV, no norm, no router, no sampling, and it\n" 426" assumes every expert is already resident in VRAM at zero cost.\n" ); 427 428// The NAIVE kernel's output is the reference for the split one. `s_gemv` is checked against the scalar 429// dequantizer by this file's parity cases, so its result here is a validated value, and the split kernel 430// sums in a different order - so this is a relative comparison, not bit equality. 431 strata::kernels::s_gemv (d_x ,d_codes ,d_scales ,nullptr ,d_y ,n_in ,n_out ,form ); 432 std::vector < float > ref_naive ((size_t )n_out ); 433check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()) 434 .memcpy (ref_naive .data (),d_y , 435ref_naive .size ()* sizeof (float )) 436 .wait ()), 437"copy naive reference" ); 438 439// ---- the row-split variant, same planes, same process ------------------- 440// Swept rather than guessed: more threads per row buys parallelism and costs a deeper reduction. 441for (int tpr : {32 ,64 ,128 ,256 }) { 442if (tpr > n_in )continue ; 443for (int i = 0 ;i < 3 ;++ i ) { 444 strata::kernels::s_gemv_split (d_x ,d_codes ,d_scales ,nullptr ,d_y ,n_in ,n_out ,form ,tpr ); 445 } 446 std::vector < double > sms ; 447for (int i = 0 ;i < iters ;++ i ) { 448const auto t0 = std::chrono::steady_clock::now (); 449 strata::kernels::s_gemv_split (d_x ,d_codes ,d_scales ,nullptr ,d_y ,n_in ,n_out ,form ,tpr ); 450sms .push_back (std::chrono::duration < double , std::milli > (std::chrono::steady_clock::now ()- t0 ) 451 .count ()); 452 } 453 std::sort (sms .begin (),sms .end ()); 454 455// correctness of the thing being timed 456 std::vector < float > got ((size_t )n_out ); 457check (DPCT_CHECK_ERROR ( 458 (dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()) 459 .memcpy (got .data (),d_y ,got .size ()* sizeof (float )) 460 .wait ()), 461"copy split result" ); 462long long bad = 0 ; 463double worst = 0.0 ; 464for (long long o = 0 ;o < n_out ;++ o ) { 465const double a = ref_naive [(size_t )o ],b = got [(size_t )o ]; 466const double rel = std::fabs (a - b ) / (std::fabs (a )> 1e-30 ? std::fabs (a ) :1e-30 ); 467if (!(rel <=worst ))worst = rel ; 468if (!(rel <=1e-4 ))++ bad ; 469 } 470if (bad ) { 471 std::printf (" split tpr=%-4d *** WRONG *** %lld of %lld rows differ, worst rel %.3e\n" ,tpr , 472bad ,n_out ,worst ); 473* split_bad += (int )bad ; 474 } 475 476// ---- the quad-amortised S2 kernel, timed AND checked against the naive reference ---- 477// Only meaningful for S2: it assumes four elements share one code byte, which is true of 2-bit codes. 478if (form .code_bits == 2 && (n_in %64 )== 0 ) { 479for (int t2 : {32 ,64 ,128 }) { 480for (int i = 0 ;i < 3 ;++ i ) { 481 strata::kernels::s2_gemv_quads (d_x ,d_codes ,d_scales ,d_y ,n_in ,n_out ,t2 ); 482 } 483 std::vector < double > qms ; 484for (int i = 0 ;i < iters ;++ i ) { 485const auto q0 = std::chrono::steady_clock::now (); 486 strata::kernels::s2_gemv_quads (d_x ,d_codes ,d_scales ,d_y ,n_in ,n_out ,t2 ); 487qms .push_back (std::chrono::duration < double , std::milli > ( 488 std::chrono::steady_clock::now ()- q0 ).count ()); 489 } 490 std::sort (qms .begin (),qms .end ()); 491check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()) 492 .memcpy (got .data (),d_y , 493got .size ()* sizeof (float )) 494 .wait ()), 495"copy quads result" ); 496long long qbad = 0 ; 497double qworst = 0.0 ; 498for (long long o = 0 ;o < n_out ;++ o ) { 499const double a = ref_naive [(size_t )o ],b = got [(size_t )o ]; 500const double rel = std::fabs (a - b ) / (std::fabs (a )> 1e-30 ? std::fabs (a ) :1e-30 ); 501if (rel > qworst )qworst = rel ; 502if (!(rel <=1e-4 ))++ qbad ; 503 } 504if (qbad )* split_bad += (int )qbad ; 505 std::printf (" quads tpr=%-4d min %.4f ms -> %6.1f G weights/s vs naive %.2fx %s\n" ,t2 , 506qms .front (),weights /qms .front () /1e6 ,ms .front () /qms .front (), 507qbad ?"*** WRONG ***" :"checked ok" ); 508 } 509 } 510 511// ---- the two-lever kernel, both configurations, timed AND checked ---- 512if (form .code_bits == 2 && (n_in %64 )== 0 ) { 513for (int staged = 0 ;staged < 2 ;++ staged ) { 514for (int t3 : {32 ,64 ,128 }) { 515for (int i = 0 ;i < 3 ;++ i ) { 516 strata::kernels::s2_gemv_fast (d_x ,d_codes ,d_scales ,d_y ,n_in ,n_out ,t3 ,staged != 0 ); 517 } 518 std::vector < double > fms ; 519for (int i = 0 ;i < iters ;++ i ) { 520const auto q0 = std::chrono::steady_clock::now (); 521 strata::kernels::s2_gemv_fast (d_x ,d_codes ,d_scales ,d_y ,n_in ,n_out ,t3 ,staged != 0 ); 522fms .push_back (std::chrono::duration < double , std::milli > ( 523 std::chrono::steady_clock::now ()- q0 ).count ()); 524 } 525 std::sort (fms .begin (),fms .end ()); 526check ( 527DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()) 528 .memcpy (got .data (),d_y , 529got .size ()* sizeof (float )) 530 .wait ()), 531"copy fast result" ); 532long long fbad = 0 ; 533for (long long o = 0 ;o < n_out ;++ o ) { 534const double a = ref_naive [(size_t )o ],b = got [(size_t )o ]; 535const double rel = std::fabs (a - b ) / (std::fabs (a )> 1e-30 ? std::fabs (a ) :1e-30 ); 536if (!(rel <=1e-4 ))++ fbad ; 537 } 538if (fbad )* split_bad += (int )fbad ; 539 std::printf (" fast %s tpr=%-4d min %.4f ms -> %6.1f G weights/s vs naive %.2fx %s\n" , 540staged ?"staged" :"global" ,t3 ,fms .front (), 541weights /fms .front () /1e6 ,ms .front () /fms .front (), 542fbad ?"*** WRONG ***" :"checked ok" ); 543 } 544 } 545 } 546 547const double sp = ms .front () /sms .front (); 548 std::printf (" split tpr=%-4d min %.4f ms -> %6.1f G weights/s speedup vs naive %.2fx\n" ,tpr , 549sms .front (),weights /sms .front () /1e6 ,sp ); 550 } 551 552 sycl::free (d_x , dpct::get_in_order_queue ()); 553 sycl::free (d_codes , dpct::get_in_order_queue ()); 554 sycl::free (d_scales , dpct::get_in_order_queue ()); 555 sycl::free (d_y , dpct::get_in_order_queue ()); 556} 557 558int main (int argc ,char ** argv ) { 559long long n_in = 2560 ; 560long long n_out = 128 ; 561// 1e-4, not 1e-5: the measured worst is ~1e-5 (FMA contraction of a 2560-term f32 accumulation), so a 562// 1e-5 threshold would pass by 4% and fail on a different n_in. The phase spec allows 1e-3 for FP16 563// paths; this is 10x tighter than the spec and 10x looser than the measurement. 564double tol = 1e-4 ; 565bool selftest = false; 566bool bench = false; 567int iters = 200 ; 568for (int i = 1 ;i < argc ;++ i ) { 569const std::string a = argv [i ]; 570if (a == "--selftest" )selftest = true; 571else if (a == "--bench" )bench = true; 572else if (a == "--iters" && i + 1 < argc )iters = std::atoi (argv [++ i ]); 573else if (a == "--n-in" && i + 1 < argc )n_in = std::atoll (argv [++ i ]); 574else if (a == "--n-out" && i + 1 < argc )n_out = std::atoll (argv [++ i ]); 575else { 576 std::fprintf (stderr ,"usage: s_gemv_parity [--selftest] [--n-in N] [--n-out N]\n" ); 577return 2 ; 578 } 579 } 580 581using strata::kernels::Codebook ; 582using strata::kernels::SForm ; 583 std::vector < Case > cases ; 584cases .push_back ({"S2/Q2_0" ,SForm {2 ,-1 ,64 ,Codebook ::Affine , false},18 ,q2_0_to_raw ,q2_0_deq }); 585cases .push_back ({"S4/Q4_0" ,SForm {4 ,-8 ,32 ,Codebook ::Affine , false},18 ,q4_0_to_raw ,q4_0_deq }); 586cases .push_back ({"S4/IQ4_NL" ,SForm {4 ,0 ,32 ,Codebook ::Iq4Nl , false},18 ,iq4_to_raw ,iq4_deq }); 587cases .push_back ({"S8/Q8_0" ,SForm {8 ,-128 ,32 ,Codebook ::Affine , false},34 ,q8_0_to_raw ,q8_0_deq }); 588 589 std::mt19937 rng (4242 ); 590const int n_scales = (int ) (sizeof (kScales ) /sizeof (kScales [0 ])); 591int total_bad = 0 ; 592 593for (const Case & tc :cases ) { 594const int bits = tc .form .code_bits ; 595const int per_byte = 8 /bits ; 596const int G = tc .form .group_elems ; 597const long long n_groups = n_in /G ; 598const long long codes_per_row = n_in /per_byte ; 599 600// activations 601 std::vector < uint16_t > x ((size_t )n_in ); 602for (long long i = 0 ;i < n_in ;++ i )x [(size_t )i ]= kScales [rng () %n_scales ]; 603 604// Codes are generated ONE PER ELEMENT and then packed into the plane the kernel reads. 605// 606// The first version of this test generated a random BYTE ARRAY and used it as both, which is the bug 607// that made S2 pass and the other three fail by 50x-500x. The two are not the same thing: the kernel 608// reads element i from byte i/per_byte at bit (i%per_byte)*bits, while the reference needs one code per 609// element to rebuild a raw GGUF block. For S2 (per_byte = 4, which IS Q2_0's own raw layout) treating 610// one random array as both happened to agree - and that coincidence is exactly what a test must not 611// depend on. 612 std::vector < uint8_t > codes_el ((size_t )n_out * n_in ); 613for (size_t i = 0 ;i < codes_el .size ();++ i )codes_el [i ]= (uint8_t ) (rng ()& ((1u <<bits )- 1 )); 614 std::vector < uint8_t > codes ((size_t )n_out * codes_per_row ,0 ); 615for (long long o = 0 ;o < n_out ;++ o ) { 616for (long long i = 0 ;i < n_in ;++ i ) { 617const long long byi = o * codes_per_row + i /per_byte ; 618codes [(size_t )byi ] |= (uint8_t ) (codes_el [(size_t ) (o * n_in + i )] 619 << ((i %per_byte )* bits )); 620 } 621 } 622 std::vector < float > scales ((size_t )n_out * n_groups ); 623 std::vector < uint16_t > scale_bits ((size_t )n_out * n_groups ); 624for (size_t i = 0 ;i < scales .size ();++ i ) { 625scale_bits [i ]= kScales [rng () %n_scales ]; 626scales [i ]= strata::fp16_to_fp32 (scale_bits [i ]); 627 } 628 629// CPU reference 630 std::vector < float > ref ((size_t )n_out ,0.0f ); 631 std::vector < uint8_t > raw ((size_t )tc .raw_bytes ); 632 std::vector < float > dec ((size_t )G ); 633for (long long o = 0 ;o < n_out ;++ o ) { 634float acc = 0.0f ; 635for (long long g = 0 ;g < n_groups ;++ g ) { 636const size_t co = (size_t )o * n_in + (size_t )g * G ;// the UNPACKED code array 637const size_t so = (size_t )o * n_groups + (size_t )g ; 638// The raw block carries the scale as fp16 and the canonical plane carries it widened, so the 639// block is rebuilt from the PATTERN the plane came from. No float-to-fp16 conversion is 640// needed anywhere, and the decoder therefore sees bit-identically what the kernel reads. 641const int n = tc .to_raw (codes_el .data (),co ,scale_bits .data (),so ,raw .data ()); 642tc .dequant (raw .data (),dec .data ()); 643for (long long j = 0 ;j < (long long )n ;++ j ) { 644acc += dec [(size_t )j ]* strata::fp16_to_fp32 (x [(size_t ) (g * G + j )]); 645 } 646 } 647ref [(size_t )o ]= acc ; 648 } 649 650// GPU 651uint16_t * d_x = nullptr ; 652uint8_t * d_codes = nullptr ; 653float * d_scales = nullptr ,* d_y = nullptr ; 654check (DPCT_CHECK_ERROR (d_x = sycl::malloc_device < uint16_t > ( 655x .size (), dpct::get_in_order_queue ())), 656"cudaMalloc x" ); 657check (DPCT_CHECK_ERROR (d_codes = (uint8_t * )sycl::malloc_device ( 658codes .size (), dpct::get_in_order_queue ())), 659"cudaMalloc codes" ); 660check (DPCT_CHECK_ERROR (d_scales = sycl::malloc_device < float > ( 661scales .size (), dpct::get_in_order_queue ())), 662"cudaMalloc scales" ); 663check (DPCT_CHECK_ERROR (d_y = sycl::malloc_device < float > ( 664 (size_t )n_out , dpct::get_in_order_queue ())), 665"cudaMalloc y" ); 666/* 667DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, 668assuming in the original code the source host memory is pageable memory. 669If the memory is not pageable, call wait() on event return by memcpy API 670to ensure synchronization behavior. 671*/ 672check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy ( 673d_x ,x .data (),x .size ()* sizeof (uint16_t )).wait ()), 674"copy x" ); 675/* 676DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, 677assuming in the original code the source host memory is pageable memory. 678If the memory is not pageable, call wait() on event return by memcpy API 679to ensure synchronization behavior. 680*/ 681check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy ( 682d_codes ,codes .data (),codes .size ()).wait ()), 683"copy codes" ); 684/* 685DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, 686assuming in the original code the source host memory is pageable memory. 687If the memory is not pageable, call wait() on event return by memcpy API 688to ensure synchronization behavior. 689*/ 690check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy ( 691d_scales ,scales .data (),scales .size ()* sizeof (float )).wait ()), 692"copy scales" ); 693 strata::kernels::s_gemv (d_x ,d_codes ,d_scales ,nullptr ,d_y ,n_in ,n_out ,tc .form ); 694 std::vector < float > got ((size_t )n_out ); 695check (DPCT_CHECK_ERROR ( 696 (dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()) 697 .memcpy (got .data (),d_y ,got .size ()* sizeof (float )) 698 .wait ()), 699"copy back" ); 700 701long long bad = 0 ; 702double worst = 0.0 ; 703for (long long o = 0 ;o < n_out ;++ o ) { 704const double a = ref [(size_t )o ],b = got [(size_t )o ]; 705const double rel = std::fabs (a - b ) / (std::fabs (a )> 1e-30 ? std::fabs (a ) :1e-30 ); 706if (!(rel <=worst ))worst = rel ; 707if (!(rel <=tol ))++ bad ; 708 } 709double lo = ref [0 ],hi = ref [0 ]; 710for (float v :ref ) { 711lo = std::fmin (lo ,v ); 712hi = std::fmax (hi ,v ); 713 } 714 std::printf (" %-10s %lld rows, %lld over tol, worst rel %.3e ref spread [%.4g, %.4g]\n" ,tc .name , 715n_out ,bad ,worst ,lo ,hi ); 716if (hi - lo <=0.0 ) { 717 std::fprintf (stderr ,"VACUOUS: %s reference is constant\n" ,tc .name ); 718return 1 ; 719 } 720total_bad += (int )bad ; 721 722 sycl::free (d_x , dpct::get_in_order_queue ()); 723 sycl::free (d_codes , dpct::get_in_order_queue ()); 724 sycl::free (d_scales , dpct::get_in_order_queue ()); 725 sycl::free (d_y , dpct::get_in_order_queue ()); 726 } 727 728 std::printf ("s_gemv: %zu type cases, %d rows over tolerance (tol %.1e)\n" ,cases .size (),total_bad ,tol ); 729// Q4_K IS NOT PART OF THE DEFAULT RUN. It FAILS: 128 of 128 rows, worst error 0.586 of sum|term| - a 730// real difference, not cancellation (the condition number is 2.8e7 and the error is 1.6e7). Either the 731// kernel's offset handling or this test's reconstruction of a Q4_K block is wrong and the two have not 732// been separated yet. Running it by default would turn ctest red and hide regressions in the four cases 733// that ARE verified; leaving it out silently would be worse. It is one flag away, and it is recorded as 734// OPEN in the project state. 735// Q4_K is IN the default run as of round 171. Rounds 169-170 gated it because it FAILED, and the 736// failure was this test's own reconstruction of a Q4_K block - four decodes of a quarter-filled block per 737// superblock - not the kernel. It now agrees to 2.8e-07 of sum|term|, so the gate goes rather than 738// staying as a habit: a gate that outlives its reason is a check that quietly stopped running. 739test_q4k (n_in ,n_out ,tol ,& total_bad ); 740 std::printf ("s_gemv total: %d rows over tolerance\n" ,total_bad ); 741if (bench ) { 742// the real expert shapes: gate/up are [2560 x 640], down is [640 x 2560] 743int split_bad = 0 ; 744bench_s2_gemv (2560 ,640 ,iters ,& split_bad ); 745bench_s2_gemv (640 ,2560 ,iters ,& split_bad ); 746 std::printf ("split kernel rows disagreeing with the naive reference: %d\n" ,split_bad ); 747// accumulated HERE, inside the block that declares it, and it makes the binary FAIL: a kernel that is 748// benchmarked but never compared is an unverified kernel being quoted for performance. 749total_bad += split_bad ; 750 } 751if (total_bad )return 1 ; 752if (selftest ) std::printf ("s_gemv_parity OK\n" ); 753return 0 ; 754}