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