okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
5af104b51
main
1// src/kernels/kv_stream_parity.cpp - KV streaming (kv_stream.hpp) against a fully resident pool (GPU, no model). 2// 3// Decodes a synthetic sequence twice: into a fully resident pool with the identity page table, and into a streamed 4// layer (host copy + a small VRAM slot pool that must evict constantly). Every few cells a batch of 1-8 queries 5// with selections shaped like the indexer's (whole 4-cell blocks, a partial threshold block, the tail block, half of 6// them recent) is attended in both; `kv_stream_resolve` runs before the streamed attention. Checks: 7// 1. the attention outputs are BITWISE equal (the streamed readers see exactly the resident values); 8// 2. the residency map is consistent after every call (slot_block and page_table invert each other); 9// 3. no call overflowed, and the hit/miss counters add up; 10// 4. a ring (the MTP drafter's layout) restored from the host copy reads the same values as the resident pool. 11// INT8, FP16, Q4_0 (PR #21) and hybrid K8V4 pools; K8V4's appends are the engine's folded calls (layer.cpp), its host 12// copy written through kv_hybrid_k_half / kv_hybrid_v_half. 13#define DPCT_PROFILING_ENABLED 14#include <sycl/sycl.hpp> 15#include <dpct/dpct.hpp> 16#include "strata/kernels/kv_q4.hpp" 17#include "strata/kernels/kv_q8.hpp" 18#include "strata/kernels/kv_stream.hpp" 19#include "strata/kernels/qsa.hpp" 20#include "strata/kernels/qsa_decode_attn.hpp" 21 22#include <algorithm> 23#include <cstdio> 24#include <cstdlib> 25#include <cstring> 26#include <random> 27#include <set> 28#include <vector> 29 30namespace k= strata::kernels; 31 32namespace { 33int g_fail = 0 ; 34void ck (dpct::err0 e ,const char * w ) { 35/* 36DPCT1009: SYCL reports errors using exceptions and does not use error 37codes. Please replace the "get_error_string_dummy(...)" with a real 38error-handling function. 39*/ 40} 41template < typename T > T * dalloc (size_t n ) { 42T * p = nullptr ; 43ck (DPCT_CHECK_ERROR (p = (T * )sycl::malloc_device ( 44n * sizeof (T )+ 64 , dpct::get_in_order_queue ())), 45"malloc" ); 46ck (DPCT_CHECK_ERROR ( 47 (dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memset (p ,0 ,n * sizeof (T )+ 64 ).wait ()), 48"memset" ); 49return p ; 50} 51template < typename T > T * halloc (size_t n ) {// pinned, mapped; returns the device pointer 52void * h = nullptr ; 53void * d = nullptr ; 54/* 55DPCT1048: The original value cudaHostAllocMapped is not meaningful in the 56migrated code and was removed or replaced with 0. You may need to check the 57migrated code. 58*/ 59ck (DPCT_CHECK_ERROR (h = (void * )sycl::malloc_host ( 60n * sizeof (T )+ 64 , dpct::get_in_order_queue ())), 61"hostalloc" ); 62 std::memset (h ,0 ,n * sizeof (T )+ 64 ); 63ck (DPCT_CHECK_ERROR (d = (void * )h ),"devptr" ); 64return (T * )d ; 65} 66 67struct Pools {// one K/V pool set of `pages` pages 68 k::KvHostPools p ;// reused as a plain pointer bundle 69void alloc (int64_t pages ,const k::QsaShapes & s ,int fmt ,bool host ) { 70const size_t rows = (size_t )pages * s .n_head_kv * s .page_size ; 71if (fmt == k::kKvHybrid ) { 72const size_t b = rows * k::kv_q4_bytes_per_head ((int )s .head_dim ); 73p .k_q = host ?halloc < int8_t > (rows * s .head_dim ) :dalloc < int8_t > (rows * s .head_dim ); 74p .k_scale = host ?halloc < uint16_t > (rows * 4 ) :dalloc < uint16_t > (rows * 4 ); 75p .v_q4 = host ?halloc < uint8_t > (b ) :dalloc < uint8_t > (b ); 76 }else if (fmt == k::kKvQ4 ) { 77const size_t b = rows * k::kv_q4_bytes_per_head ((int )s .head_dim ); 78p .k_q4 = host ?halloc < uint8_t > (b ) :dalloc < uint8_t > (b ); 79p .v_q4 = host ?halloc < uint8_t > (b ) :dalloc < uint8_t > (b ); 80 }else if (fmt == k::kKvInt8 ) { 81p .k_q = host ?halloc < int8_t > (rows * s .head_dim ) :dalloc < int8_t > (rows * s .head_dim ); 82p .v_q = host ?halloc < int8_t > (rows * s .head_dim ) :dalloc < int8_t > (rows * s .head_dim ); 83p .k_scale = host ?halloc < uint16_t > (rows * 4 ) :dalloc < uint16_t > (rows * 4 ); 84p .v_scale = host ?halloc < uint16_t > (rows * 4 ) :dalloc < uint16_t > (rows * 4 ); 85 }else { 86p .k_pool = host ?halloc < uint16_t > (rows * s .head_dim ) :dalloc < uint16_t > (rows * s .head_dim ); 87p .v_pool = host ?halloc < uint16_t > (rows * s .head_dim ) :dalloc < uint16_t > (rows * s .head_dim ); 88 } 89 } 90 k::QsaAttnPools attn (const int32_t * table )const { 91 k::QsaAttnPools a ; 92a .k_pool = p .k_pool ;a .v_pool = p .v_pool ;a .k_q = p .k_q ;a .v_q = p .v_q ;a .k_scale = p .k_scale ; 93a .v_scale = p .v_scale ;a .k_q4 = p .k_q4 ;a .v_q4 = p .v_q4 ;a .page_table = table ; 94return a ; 95 } 96}; 97 98void append (const Pools & pl ,const int32_t * table ,const int32_t * step ,const float * kc ,const float * vc , 99const k::QsaShapes & s ,int fmt ,const k::KvHostPools * host ) { 100if (fmt == k::kKvHybrid ) {// exactly as qsa_layer: each half folded onto its own pool, host copy by halves 101const k::KvHostPools hk = host ? k::kv_hybrid_k_half (* host ) : k::KvHostPools {}, 102hv = host ? k::kv_hybrid_v_half (* host ) : k::KvHostPools {}; 103 k::kv_append_q8_step (pl .p .k_q ,pl .p .k_q ,pl .p .k_scale ,pl .p .k_scale ,table ,step ,kc ,kc ,s ,nullptr , 104host ?& hk :nullptr ); 105 k::kv_append_q4_step (pl .p .v_q4 ,pl .p .v_q4 ,table ,step ,vc ,vc ,s ,nullptr ,host ?& hv :nullptr ); 106 }else if (fmt == k::kKvQ4 ) k::kv_append_q4_step (pl .p .k_q4 ,pl .p .v_q4 ,table ,step ,kc ,vc ,s ,nullptr ,host ); 107else if (fmt == k::kKvInt8 ) k::kv_append_q8_step (pl .p .k_q ,pl .p .v_q ,pl .p .k_scale ,pl .p .v_scale ,table ,step ,kc ,vc ,s ,nullptr ,host ); 108else k::kv_append_step (pl .p .k_pool ,pl .p .v_pool ,table ,step ,kc ,vc ,s ,nullptr ,host ); 109} 110 111// A selection like qsa_block_topk's: ascending cells, whole blocks, the tail block's cells, and one partial block. 112std::vector < int32_t > selection (int64_t n_kv ,int64_t width , std::mt19937 & rng ) { 113 std::vector < int32_t > ids ; 114if (n_kv <=width ) { 115for (int64_t c = 0 ;c < n_kv ;++ c )ids .push_back ((int32_t )c ); 116return ids ; 117 } 118const int64_t n_bid = n_kv /4 ,tail = n_kv - n_bid * 4 ; 119 std::set < int64_t > blocks ; 120const int64_t want_full = (width - tail ) /4 ,part = (width - tail ) %4 ; 121 std::uniform_int_distribution < int64_t > any (0 ,n_bid - 1 ),recent (std::max < int64_t > (0 ,n_bid - 2048 ),n_bid - 1 ); 122while ((int64_t )blocks .size ()< want_full + (part ?1 :0 ))blocks .insert (rng () %2 ?recent (rng ) :any (rng )); 123int64_t partial_block = part ?* std::next (blocks .begin (), (long ) (rng () %blocks .size ())) :-1 ; 124for (int64_t b :blocks ) { 125const int64_t take = b == partial_block ?part :4 ; 126for (int64_t i = 0 ;i < take ;++ i )ids .push_back ((int32_t ) (b * 4 + i )); 127 } 128for (int64_t c = n_bid * 4 ;c < n_kv ;++ c )ids .push_back ((int32_t )c ); 129 std::sort (ids .begin (),ids .end ()); 130return ids ; 131} 132 133bool run (int fmt ) { 134const char * name = fmt == k::kKvHybrid ?"k8v4" :fmt == k::kKvQ4 ?"q4_0" :fmt == k::kKvInt8 ?"int8" :"fp16" ; 135 k::QsaShapes s = k::qsa_real_shapes (); 136const int64_t N = 40000 ,n_blocks = (N + 3 ) /4 ,n_slots = 8 * 516 + 700 ;// must evict: slots < blocks 137const int64_t cap = k::qsa_selection_width (k::kTopkMaxCells ,s ),NQ = 8 ; 138const int64_t H = s .n_head_kv ,D = s .head_dim ,NH = s .n_head ; 139 std::mt19937 rng (7 + 4 * fmt ); 140 std::normal_distribution < float > nd (0.f ,1.f ); 141 142Pools ref ,slots ,host ; 143ref .alloc (n_blocks ,s ,fmt , false); 144slots .alloc (n_slots ,s ,fmt , false); 145host .alloc (n_blocks ,s ,fmt , true); 146int32_t * ident = dalloc < int32_t > (n_blocks ); 147 { 148 std::vector < int32_t > t (n_blocks ); 149for (int64_t i = 0 ;i < n_blocks ;++ i )t [i ]= (int32_t )i ; 150/* 151DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, 152assuming in the original code the source host memory is pageable memory. 153If the memory is not pageable, call wait() on event return by memcpy API 154to ensure synchronization behavior. 155*/ 156ck (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy (ident ,t .data (), 157n_blocks * 4 ).wait ()), 158"ident" ); 159 } 160 k::KvStreamMap m ; 161m .page_table = dalloc < int32_t > (n_blocks ); 162m .slot_block = dalloc < int32_t > (n_slots );m .slot_stamp = dalloc < int32_t > (n_slots );m .slot_ref = dalloc < int32_t > (n_slots ); 163m .miss_block = dalloc < int32_t > (n_slots );m .miss_slot = dalloc < int32_t > (n_slots ); 164m .ctl = dalloc < int32_t > (k::kKvCtlInts ); 165m .n_blocks = n_blocks ;m .n_slots = n_slots ; 166 k::kv_stream_reset (m ,nullptr ); 167 168float * kc = dalloc < float > (H * D ); 169float * vc = dalloc < float > (H * D ); 170int32_t * step = dalloc < int32_t > (k::kStepCount ); 171int32_t * steps = dalloc < int32_t > (NQ * k::kStepCount ); 172int32_t * ids = dalloc < int32_t > (NQ * cap ); 173float * q = dalloc < float > (NQ * NH * D ); 174const uint64_t scr = k::qsa_decode_attn_scratch_floats (cap ,s ); 175float * scratch = dalloc < float > (NQ * scr ); 176float * out_ref = dalloc < float > (NQ * NH * D ); 177float * out_str = dalloc < float > (NQ * NH * D ); 178 std::vector < float > hk (H * D ),hv (H * D ),hq (NQ * NH * D ),a ((size_t )NQ * NH * D ),b2 ((size_t )NQ * NH * D ); 179 std::vector < int32_t > pt (n_blocks ),sb (n_slots ); 180 181int batches = 0 ,bad = 0 ; 182for (int64_t pos = 0 ;pos < N ;++ pos ) { 183for (auto & x :hk )x = nd (rng )* ((pos %17 == 0 ) ?30.f :1.f ); 184for (auto & x :hv )x = nd (rng ); 185const int32_t st [4 ]= {(int32_t )pos , (int32_t ) (pos + 1 ), (int32_t ) ((pos + 1 ) /4 ),0 }; 186/* 187DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, 188assuming in the original code the source host memory is pageable memory. 189If the memory is not pageable, call wait() on event return by memcpy API 190to ensure synchronization behavior. 191*/ 192ck (DPCT_CHECK_ERROR ( 193 (dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy (kc ,hk .data (),hk .size ()* 4 ).wait ()), 194"k" ); 195/* 196DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, 197assuming in the original code the source host memory is pageable memory. 198If the memory is not pageable, call wait() on event return by memcpy API 199to ensure synchronization behavior. 200*/ 201ck (DPCT_CHECK_ERROR ( 202 (dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy (vc ,hv .data (),hv .size ()* 4 ).wait ()), 203"v" ); 204/* 205DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, 206assuming in the original code the source host memory is pageable memory. 207If the memory is not pageable, call wait() on event return by memcpy API 208to ensure synchronization behavior. 209*/ 210ck (DPCT_CHECK_ERROR ( 211 (dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy (step ,st ,sizeof (st )).wait ()), 212"step" ); 213append (ref ,ident ,step ,kc ,vc ,s ,fmt ,nullptr ); 214append (slots ,m .page_table ,step ,kc ,vc ,s ,fmt ,& host .p ); 215if (pos %131 != 130 && pos != N - 1 )continue ; 216// a batch: n_q queries at the last n_q positions (as a verify window), each with its own selection 217const int n_q = 1 + (int ) (rng () %NQ ); 218 std::vector < int32_t > hids ((size_t )NQ * cap ,0 ),hst (NQ * 4 ,0 ); 219for (int t = 0 ;t < n_q ;++ t ) { 220const int64_t p = std::max < int64_t > (0 ,pos - (n_q - 1 - t )),n_kv = p + 1 ; 221const int64_t width = std::min < int64_t > (n_kv ,cap ); 222const std::vector < int32_t > sel = selection (n_kv ,width ,rng ); 223if ((int64_t )sel .size ()!= width ) { std::fprintf (stderr ,"selection size %zu != %lld\n" ,sel .size (), (long long )width );return false; } 224 std::copy (sel .begin (),sel .end (),hids .begin ()+ (size_t )t * cap ); 225hst [t * 4 + 0 ]= (int32_t )p ;hst [t * 4 + 1 ]= (int32_t )n_kv ;hst [t * 4 + 2 ]= (int32_t ) (n_kv /4 ); 226hst [t * 4 + 3 ]= (int32_t )width ; 227 } 228for (auto & x :hq )x = nd (rng ); 229/* 230DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, 231assuming in the original code the source host memory is pageable memory. 232If the memory is not pageable, call wait() on event return by memcpy API 233to ensure synchronization behavior. 234*/ 235ck (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy (ids ,hids .data (), 236hids .size ()* 4 ).wait ()), 237"ids" ); 238/* 239DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, 240assuming in the original code the source host memory is pageable memory. 241If the memory is not pageable, call wait() on event return by memcpy API 242to ensure synchronization behavior. 243*/ 244ck (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy (steps ,hst .data (), 245hst .size ()* 4 ).wait ()), 246"steps" ); 247/* 248DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, 249assuming in the original code the source host memory is pageable memory. 250If the memory is not pageable, call wait() on event return by memcpy API 251to ensure synchronization behavior. 252*/ 253ck (DPCT_CHECK_ERROR ( 254 (dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy (q ,hq .data (),hq .size ()* 4 ).wait ()), 255"q" ); 256 k::qsa_decode_attn_batch (q ,ref .attn (ident ),ids ,steps ,cap ,s ,scratch ,out_ref ,n_q ,nullptr ); 257 k::kv_stream_resolve (m ,slots .attn (m .page_table ),host .p ,fmt ,ids ,steps ,n_q ,cap ,s ,nullptr ); 258 k::qsa_decode_attn_batch (q ,slots .attn (m .page_table ),ids ,steps ,cap ,s ,scratch ,out_str ,n_q ,nullptr ); 259ck (DPCT_CHECK_ERROR (dpct::get_current_device ().queues_wait_and_throw ()), 260"batch" ); 261ck (DPCT_CHECK_ERROR ( 262 (dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()) 263 .memcpy (a .data (),out_ref , (size_t )n_q * NH * D * 4 ) 264 .wait ()), 265"a" ); 266ck (DPCT_CHECK_ERROR ( 267 (dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()) 268 .memcpy (b2 .data (),out_str , (size_t )n_q * NH * D * 4 ) 269 .wait ()), 270"b" ); 271if (std::memcmp (a .data (),b2 .data (), (size_t )n_q * NH * D * 4 )!= 0 ) { 272if (bad ++ < 5 ) std::fprintf (stderr ," %s pos %lld n_q %d: streamed attention differs\n" ,name , (long long )pos ,n_q ); 273 } 274// the map inverts itself 275ck (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()) 276 .memcpy (pt .data (),m .page_table ,n_blocks * 4 ) 277 .wait ()), 278"pt" ); 279ck (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()) 280 .memcpy (sb .data (),m .slot_block ,n_slots * 4 ) 281 .wait ()), 282"sb" ); 283int64_t resident = 0 ; 284for (int64_t bk = 0 ;bk < n_blocks ;++ bk ) { 285if (pt [bk ]< -1 || pt [bk ] >=n_slots || (pt [bk ] >=0 && sb [pt [bk ]]!= bk )) { 286if (bad ++ < 5 ) std::fprintf (stderr ," map broken at block %lld (table %d)\n" , (long long )bk ,pt [bk ]); 287break ; 288 } 289resident += pt [bk ] >=0 ; 290 } 291for (int64_t sl = 0 ;sl < n_slots ;++ sl ) 292if (sb [sl ] >=0 && pt [sb [sl ]]!= sl ) {if (bad ++ < 5 ) std::fprintf (stderr ," slot %lld not in the table\n" , (long long )sl );break ; } 293++ batches ; 294 } 295const k::KvStreamCounters c = k::kv_stream_counters (m ); 296 std::printf (" %s: %d batches, %llu block lookups, %llu misses (%.1f%% hit), overflow %d, %d failures\n" , 297name ,batches , (unsigned long long )c .lookups , (unsigned long long )c .misses , 298c .lookups ?100.0 * (double ) (c .lookups - c .misses ) / (double )c .lookups :0.0 , (int )c .overflow ,bad ); 299if (c .overflow || c .calls != (uint64_t )batches || c .misses == 0 || c .misses >=c .lookups )++ bad ; 300 301// 4. a ring over the same host copy: blocks [b1 - R, b1) restored, read through `b % R` 302 { 303const int64_t R = 1500 ,b1 = n_blocks ,b0 = b1 - R ; 304Pools ring ; 305ring .alloc (R ,s ,fmt , false); 306int32_t * rt = dalloc < int32_t > (n_blocks ); 307 k::kv_ring_table (rt ,n_blocks ,R ,nullptr ); 308 k::kv_ring_restore (ring .attn (rt ),host .p ,fmt ,b0 ,b1 ,R ,s ,nullptr ); 309const int64_t width = cap ; 310 std::vector < int32_t > hids ((size_t )cap ),hst = {(int32_t ) (N - 1 ), (int32_t )N , (int32_t ) (N /4 ), (int32_t )width }; 311for (int64_t i = 0 ;i < width ;++ i )hids [i ]= (int32_t ) (N - width + i );// the window's last cells 312/* 313DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, 314assuming in the original code the source host memory is pageable memory. 315If the memory is not pageable, call wait() on event return by memcpy API 316to ensure synchronization behavior. 317*/ 318ck (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy (ids ,hids .data (), 319hids .size ()* 4 ).wait ()), 320"ids" ); 321/* 322DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, 323assuming in the original code the source host memory is pageable memory. 324If the memory is not pageable, call wait() on event return by memcpy API 325to ensure synchronization behavior. 326*/ 327ck (DPCT_CHECK_ERROR ( 328 (dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy (steps ,hst .data (),16 ).wait ()), 329"steps" ); 330 k::qsa_decode_attn_batch (q ,ref .attn (ident ),ids ,steps ,cap ,s ,scratch ,out_ref ,1 ,nullptr ); 331 k::qsa_decode_attn_batch (q ,ring .attn (rt ),ids ,steps ,cap ,s ,scratch ,out_str ,1 ,nullptr ); 332ck (DPCT_CHECK_ERROR (dpct::get_current_device ().queues_wait_and_throw ()), 333"ring" ); 334ck (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()) 335 .memcpy (a .data (),out_ref , (size_t )NH * D * 4 ) 336 .wait ()), 337"a" ); 338ck (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()) 339 .memcpy (b2 .data (),out_str , (size_t )NH * D * 4 ) 340 .wait ()), 341"b" ); 342const bool ok = std::memcmp (a .data (),b2 .data (), (size_t )NH * D * 4 )== 0 ; 343 std::printf (" %s ring restore: %s\n" ,name ,ok ?"identical" :"DIFFERS" ); 344if (!ok )++ bad ; 345 } 346return bad == 0 ; 347} 348}// namespace 349 350int main () { 351 std::printf ("kv_stream_parity: streamed vs resident KV, bitwise\n" ); 352const bool a = run (k::kKvInt8 ),b = run (k::kKvF16 ),c = run (k::kKvQ4 ),d = run (k::kKvHybrid ); 353if (!a || !b || !c || !d )++ g_fail ; 354 std::printf (g_fail ?"FAIL\n" :"PASS\n" ); 355return g_fail ?1 :0 ; 356}