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