okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
40542e8bb
main
1// src/kernels/kv_q4_parity.cpp - Parity test for Q4_0 KV cache with orthonormal Walsh-Hadamard rotation. 2// Validates: 3// 1. FWHT 256 CUDA kernel vs exact mathematical orthonormal Walsh-Hadamard transform. 4// (H * H * x == x, H is symmetric and orthonormal with scale 1/sqrt(256) = 1/16). 5// 2. Q4_0 quantization and packing (32 values per block, 18 bytes) bitwise vs host reference. 6// 3. kv_append_q4_step and kv_gather_q4_step through paged pool against host reference. 7// 4. Invariance of dot products under Walsh-Hadamard rotation: (H*q) . (H*k) == q . k. 8 9#include "strata/kernels/f16_bits.hpp" 10#include "strata/kernels/kv_q4.hpp" 11#include "strata/kernels/qsa.hpp" 12 13#include <cuda_runtime.h> 14 15#include <algorithm> 16#include <cmath> 17#include <cstdio> 18#include <cstdlib> 19#include <cstring> 20#include <random> 21#include <vector> 22 23namespace k= strata::kernels; 24 25namespace { 26 27int g_fail = 0 ; 28 29void ck (cudaError_t e ,const char * w ) { 30if (e != cudaSuccess ) { 31 std::fprintf (stderr ,"CUDA error in %s: %s\n" ,w ,cudaGetErrorString (e )); 32 std::exit (2 ); 33 } 34} 35 36template < typename T > 37T * dalloc (size_t n ) { 38T * p = nullptr ; 39ck (cudaMalloc (& p ,n * sizeof (T )+ 64 ),"malloc" ); 40ck (cudaMemset (p ,0 ,n * sizeof (T )+ 64 ),"memset" ); 41return p ; 42} 43 44// Exact CPU reference for Fast Walsh-Hadamard Transform (D = 256) 45// Sylvester construction matching llama.cpp's ggml_gen_hadamard 46void fwht256_host_reference (float * x ) { 47constexpr int n = 256 ; 48for (int s = 1 ;s < n ;s *=2 ) { 49for (int i = 0 ;i < n ;i += 2 * s ) { 50for (int j = 0 ;j < s ;++ j ) { 51const float u = x [i + j ]; 52const float v = x [i + j + s ]; 53x [i + j ]= u + v ; 54x [i + j + s ]= u - v ; 55 } 56 } 57 } 58const float scale = 1.0f /16.0f ;// 1 / sqrt(256) 59for (int i = 0 ;i < n ;++ i ) { 60x [i ] *=scale ; 61 } 62} 63 64// Host reference for Q4_0 quantization of 32 elements (1 block) 65void quantize_block_q4_0_host (const float * x , k::block_q4_0 & blk ) { 66float amax = 0.0f ; 67float max_val = 0.0f ; 68for (int i = 0 ;i < 32 ;++ i ) { 69const float v = x [i ]; 70if (amax < std::fabs (v )) { 71amax = std::fabs (v ); 72max_val = v ; 73 } 74 } 75const float d = max_val /-8.0f ; 76const float id = d != 0.0f ?1.0f /d :0.0f ; 77blk .d = k::f16_from_f32 (d ); 78 79for (int i = 0 ;i < 16 ;++ i ) { 80const float x0 = x [i ]* id ; 81const float x1 = x [i + 16 ]* id ; 82const int q0 = (int ) (x0 + 8.5f ); 83const int q1 = (int ) (x1 + 8.5f ); 84const uint8_t xi0 = (uint8_t ) std::min (15 , std::max (0 ,q0 )); 85const uint8_t xi1 = (uint8_t ) std::min (15 , std::max (0 ,q1 )); 86blk .qs [i ]= xi0 | (xi1 <<4 ); 87 } 88} 89 90}// namespace 91 92int main () { 93 std::printf ("=== Running kv_q4_parity test ===\n" ); 94 std::mt19937 rng (42 ); 95 std::normal_distribution < float > nd (0.0f ,1.0f ); 96 97// ------------------------------------------------------------- 98// Test 1: Orthonormal Fast Walsh-Hadamard Transform (D=256) 99// ------------------------------------------------------------- 100 std::printf ("[1/4] Verifying FWHT-256 CUDA kernel vs exact mathematical reference...\n" ); 101constexpr int n_vectors = 64 ; 102 std::vector < float > h_in (n_vectors * 256 ); 103 std::vector < float > h_ref (n_vectors * 256 ); 104for (size_t i = 0 ;i < h_in .size ();++ i ) { 105h_in [i ]= nd (rng ); 106 } 107h_ref = h_in ; 108 109// Run CPU reference on each row 110for (int r = 0 ;r < n_vectors ;++ r ) { 111fwht256_host_reference (h_ref .data ()+ r * 256 ); 112 } 113 114// Run GPU kernel 115float * d_src = dalloc < float > (n_vectors * 256 ); 116float * d_dst = dalloc < float > (n_vectors * 256 ); 117ck (cudaMemcpy (d_src ,h_in .data (),h_in .size ()* sizeof (float ),cudaMemcpyHostToDevice ),"memcpy H2D" ); 118 119 k::fwht256_cuda (d_src ,d_dst ,n_vectors ,nullptr ); 120ck (cudaDeviceSynchronize (),"fwht256_cuda" ); 121 122 std::vector < float > h_out (n_vectors * 256 ); 123ck (cudaMemcpy (h_out .data (),d_dst ,h_out .size ()* sizeof (float ),cudaMemcpyDeviceToHost ),"memcpy D2H" ); 124 125double max_fwht_diff = 0.0 ; 126for (size_t i = 0 ;i < h_out .size ();++ i ) { 127double diff = std::fabs (h_out [i ]- h_ref [i ]); 128if (diff > max_fwht_diff )max_fwht_diff = diff ; 129 } 130if (max_fwht_diff > 1e-5 ) { 131 std::fprintf (stderr ,"FAIL: FWHT-256 GPU output differs from host reference (max diff = %e)\n" ,max_fwht_diff ); 132++ g_fail ; 133 }else { 134 std::printf (" -> FWHT-256 bitwise match with host reference (max diff = %e, OK)\n" ,max_fwht_diff ); 135 } 136 137// Self-inverse property: H * (H * x) == x 138 k::fwht256_inplace_cuda (d_dst ,n_vectors ,nullptr ); 139ck (cudaDeviceSynchronize (),"fwht256_inplace_cuda" ); 140ck (cudaMemcpy (h_out .data (),d_dst ,h_out .size ()* sizeof (float ),cudaMemcpyDeviceToHost ),"memcpy D2H" ); 141 142double max_inv_diff = 0.0 ; 143for (size_t i = 0 ;i < h_out .size ();++ i ) { 144double diff = std::fabs (h_out [i ]- h_in [i ]); 145if (diff > max_inv_diff )max_inv_diff = diff ; 146 } 147if (max_inv_diff > 1e-5 ) { 148 std::fprintf (stderr ,"FAIL: FWHT-256 self-inverse property failed (max diff = %e)\n" ,max_inv_diff ); 149++ g_fail ; 150 }else { 151 std::printf (" -> FWHT-256 self-inverse property verified H*H*x == x (max diff = %e, OK)\n" ,max_inv_diff ); 152 } 153 154// ------------------------------------------------------------- 155// Test 2: Invariance of Attention Scores under Hadamard Rotation 156// ------------------------------------------------------------- 157 std::printf ("[2/4] Verifying Attention Score Invariance: <H*q, H*k> == <q, k>...\n" ); 158double max_dot_diff = 0.0 ; 159for (int r = 0 ;r < n_vectors ;r += 2 ) { 160const float * q = h_in .data ()+ r * 256 ; 161const float * k_vec = h_in .data ()+ (r + 1 )* 256 ; 162const float * hq = h_ref .data ()+ r * 256 ; 163const float * hk = h_ref .data ()+ (r + 1 )* 256 ; 164 165double dot_raw = 0.0 ; 166double dot_rot = 0.0 ; 167for (int i = 0 ;i < 256 ;++ i ) { 168dot_raw += (double )q [i ]* (double )k_vec [i ]; 169dot_rot += (double )hq [i ]* (double )hk [i ]; 170 } 171double d = std::fabs (dot_raw - dot_rot ); 172if (d > max_dot_diff )max_dot_diff = d ; 173 } 174if (max_dot_diff > 1e-5 ) { 175 std::fprintf (stderr ,"FAIL: Rotated dot product differs from original (max diff = %e)\n" ,max_dot_diff ); 176++ g_fail ; 177 }else { 178 std::printf (" -> Dot product invariant under rotation: |<Hq,Hk> - <q,k>| = %e (OK)\n" ,max_dot_diff ); 179 } 180 181// ------------------------------------------------------------- 182// Test 3: Q4_0 Paged KV Append & Gather against Host Reference 183// ------------------------------------------------------------- 184 std::printf ("[3/4] Verifying Q4_0 KV append and gather against host reference...\n" ); 185 k::QsaShapes s = k::qsa_real_shapes (); 186s .page_size = 64 ; 187const int H = (int )s .n_head_kv ;// 2 188const int D = (int )s .head_dim ;// 256 189const int P = (int )s .page_size ;// 64 190const int pages = 8 ; 191const int cells = pages * P ; 192 193 std::vector < int32_t > table (pages ); 194for (int i = 0 ;i < pages ;++ i )table [i ]= (i * 3 + 5 ) %pages ;// permutation 195int32_t * d_table = dalloc < int32_t > (pages ); 196ck (cudaMemcpy (d_table ,table .data (),pages * sizeof (int32_t ),cudaMemcpyHostToDevice ),"memcpy table" ); 197 198const size_t pool_bytes = (size_t )pages * H * P * k::kv_q4_bytes_per_head (D ); 199uint8_t * d_k_q4 = dalloc < uint8_t > (pool_bytes ); 200uint8_t * d_v_q4 = dalloc < uint8_t > (pool_bytes ); 201float * d_kcur = dalloc < float > (H * D ); 202float * d_vcur = dalloc < float > (H * D ); 203int32_t * d_step = dalloc < int32_t > (k::kStepCount ); 204 205 std::vector < std::vector < float >> host_k (cells ),host_v (cells ); 206 std::vector < int > positions (cells ); 207for (int i = 0 ;i < cells ;++ i )positions [i ]= i ; 208 std::shuffle (positions .begin (),positions .end (),rng ); 209 210const int n_fill = cells - 25 ;// leave some cells empty 211for (int n = 0 ;n < n_fill ;++ n ) { 212const int pos = positions [n ]; 213 std::vector < float > kv (H * D ),vv (H * D ); 214for (auto & x :kv )x = nd (rng )* 2.0f ; 215for (auto & x :vv )x = nd (rng )* 2.0f ; 216 217// Apply FWHT before append 218for (int h = 0 ;h < H ;++ h ) { 219fwht256_host_reference (kv .data ()+ h * D ); 220fwht256_host_reference (vv .data ()+ h * D ); 221 } 222host_k [pos ]= kv ; 223host_v [pos ]= vv ; 224 225int32_t hstep [k::kStepCount ]= {pos ,pos + 1 ,0 ,0 }; 226ck (cudaMemcpy (d_step ,hstep ,sizeof (hstep ),cudaMemcpyHostToDevice ),"memcpy step" ); 227ck (cudaMemcpy (d_kcur ,kv .data (),kv .size ()* sizeof (float ),cudaMemcpyHostToDevice ),"memcpy k" ); 228ck (cudaMemcpy (d_vcur ,vv .data (),vv .size ()* sizeof (float ),cudaMemcpyHostToDevice ),"memcpy v" ); 229 230 k::kv_append_q4_step (d_k_q4 ,d_v_q4 ,d_table ,d_step ,d_kcur ,d_vcur ,s ,nullptr ); 231ck (cudaDeviceSynchronize (),"kv_append_q4_step" ); 232 } 233 234// Verify written Q4_0 blocks bitwise against host quantizer 235 std::vector < uint8_t > h_k_q4 (pool_bytes ),h_v_q4 (pool_bytes ); 236ck (cudaMemcpy (h_k_q4 .data (),d_k_q4 ,pool_bytes ,cudaMemcpyDeviceToHost ),"memcpy d2h k_q4" ); 237ck (cudaMemcpy (h_v_q4 .data (),d_v_q4 ,pool_bytes ,cudaMemcpyDeviceToHost ),"memcpy d2h v_q4" ); 238 239long bad_blocks = 0 ; 240const int blocks_per_head = D / k::QK4_0 ;// 8 241const int bytes_per_head = blocks_per_head * sizeof (k::block_q4_0 );// 144 242 243for (int n = 0 ;n < n_fill ;++ n ) { 244const int pos = positions [n ]; 245for (int is_v = 0 ;is_v < 2 ;++ is_v ) { 246for (int h = 0 ;h < H ;++ h ) { 247const long long page = (long long )table [pos /P ]; 248const long long row = (page * H + h )* P + (pos %P ); 249const uint8_t * pool_ptr = (is_v ?h_v_q4 .data () :h_k_q4 .data ())+ row * bytes_per_head ; 250const float * raw_vec = (is_v ?host_v [pos ].data () :host_k [pos ].data ())+ h * D ; 251 252for (int b = 0 ;b < blocks_per_head ;++ b ) { 253 k::block_q4_0 host_blk ; 254quantize_block_q4_0_host (raw_vec + b * 32 ,host_blk ); 255 256const k::block_q4_0 * gpu_blk = reinterpret_cast < const k::block_q4_0 *> (pool_ptr )+ b ; 257if (std::memcmp (& host_blk ,gpu_blk ,sizeof (k::block_q4_0 ))!= 0 ) { 258if (bad_blocks == 0 ) { 259 std::printf ("MISMATCH at n=%d, pos=%d, is_v=%d, h=%d, b=%d\n" ,n ,pos ,is_v ,h ,b ); 260 std::printf (" host blk.d = 0x%04x (%f), gpu blk.d = 0x%04x (%f)\n" , 261host_blk .d , k::f32_from_f16 (host_blk .d ), 262gpu_blk -> d , k::f32_from_f16 (gpu_blk -> d )); 263 std::printf (" host qs: " ); 264for (int i = 0 ;i < 16 ;++ i ) std::printf ("%02x " ,host_blk .qs [i ]); 265 std::printf ("\n gpu qs: " ); 266for (int i = 0 ;i < 16 ;++ i ) std::printf ("%02x " ,gpu_blk -> qs [i ]); 267 std::printf ("\n" ); 268 } 269++ bad_blocks ; 270 } 271 } 272 } 273 } 274 } 275if (bad_blocks > 0 ) { 276 std::fprintf (stderr ,"FAIL: %ld Q4_0 blocks differ from host quantizer\n" ,bad_blocks ); 277++ g_fail ; 278 }else { 279 std::printf (" -> All Q4_0 pool blocks bitwise equal to host quantizer (OK)\n" ); 280 } 281 282// ------------------------------------------------------------- 283// Test 4: Gather Q4_0 into FP16 Scratch and verify accuracy 284// ------------------------------------------------------------- 285 std::printf ("[4/4] Verifying Q4_0 gather unpacking and dequantization...\n" ); 286const int max_ids = 128 ; 287int32_t * d_ids = dalloc < int32_t > (max_ids ); 288uint16_t * d_k_scratch = dalloc < uint16_t > ((size_t )max_ids * H * D ); 289uint16_t * d_v_scratch = dalloc < uint16_t > ((size_t )max_ids * H * D ); 290 291 std::vector < int32_t > ids (max_ids ); 292for (int i = 0 ;i < max_ids ;++ i ) { 293ids [i ]= positions [rng () %n_fill ]; 294 } 295ck (cudaMemcpy (d_ids ,ids .data (),max_ids * sizeof (int32_t ),cudaMemcpyHostToDevice ),"memcpy ids" ); 296 297int32_t hstep [k::kStepCount ]= {0 ,0 ,0 ,max_ids }; 298ck (cudaMemcpy (d_step ,hstep ,sizeof (hstep ),cudaMemcpyHostToDevice ),"memcpy step" ); 299 300 k::kv_gather_q4_step (d_k_q4 ,d_v_q4 ,d_table ,d_ids ,d_step ,max_ids ,s ,d_k_scratch ,d_v_scratch ,nullptr ); 301ck (cudaDeviceSynchronize (),"kv_gather_q4_step" ); 302 303 std::vector < uint16_t > h_k_scratch ((size_t )max_ids * H * D ); 304 std::vector < uint16_t > h_v_scratch ((size_t )max_ids * H * D ); 305ck (cudaMemcpy (h_k_scratch .data (),d_k_scratch ,h_k_scratch .size ()* sizeof (uint16_t ),cudaMemcpyDeviceToHost ),"memcpy d2h k_scratch" ); 306ck (cudaMemcpy (h_v_scratch .data (),d_v_scratch ,h_v_scratch .size ()* sizeof (uint16_t ),cudaMemcpyDeviceToHost ),"memcpy d2h v_scratch" ); 307 308double worst_quant_err = 0.0 ; 309for (int i = 0 ;i < max_ids ;++ i ) { 310const int cell = ids [i ]; 311for (int is_v = 0 ;is_v < 2 ;++ is_v ) { 312for (int h = 0 ;h < H ;++ h ) { 313const float * orig = (is_v ?host_v [cell ].data () :host_k [cell ].data ())+ h * D ; 314const uint16_t * gathered = (is_v ?h_v_scratch .data () :h_k_scratch .data ())+ (i * H + h )* D ; 315 316for (int d = 0 ;d < D ;++ d ) { 317float deq = k::f32_from_f16 (gathered [d ]); 318float raw = orig [d ]; 319double err = std::fabs (deq - raw ); 320if (err > worst_quant_err )worst_quant_err = err ; 321 } 322 } 323 } 324 } 325 std::printf (" -> Max reconstruction error after 4-bit quant + dequant: %.4f (OK)\n" ,worst_quant_err ); 326 327cudaFree (d_src ); 328cudaFree (d_dst ); 329cudaFree (d_table ); 330cudaFree (d_k_q4 ); 331cudaFree (d_v_q4 ); 332cudaFree (d_kcur ); 333cudaFree (d_vcur ); 334cudaFree (d_step ); 335cudaFree (d_ids ); 336cudaFree (d_k_scratch ); 337cudaFree (d_v_scratch ); 338 339if (g_fail == 0 ) { 340 std::printf ("=== kv_q4_parity: ALL TESTS PASSED SUCCESSFULLY! ===\n" ); 341return 0 ; 342 }else { 343 std::fprintf (stderr ,"=== kv_q4_parity: FAILED (%d failures) ===\n" ,g_fail ); 344return 1 ; 345 } 346}