okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
fea9ff5a4
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#include "strata/kernels/kv_q4.hpp" 14#include "strata/kernels/kv_q8.hpp" 15#include "strata/kernels/kv_stream.hpp" 16#include "strata/kernels/qsa.hpp" 17#include "strata/kernels/qsa_decode_attn.hpp" 18 19#include <cuda_runtime.h> 20 21#include <algorithm> 22#include <cstdio> 23#include <cstdlib> 24#include <cstring> 25#include <random> 26#include <set> 27#include <vector> 28 29namespace k= strata::kernels; 30 31namespace { 32int g_fail = 0 ; 33void ck (cudaError_t e ,const char * w ) { 34if (e != cudaSuccess ) { std::fprintf (stderr ,"%s: %s\n" ,w ,cudaGetErrorString (e )); std::exit (2 ); } 35} 36template < typename T > T * dalloc (size_t n ) { 37T * p = nullptr ; 38ck (cudaMalloc (& p ,n * sizeof (T )+ 64 ),"malloc" ); 39ck (cudaMemset (p ,0 ,n * sizeof (T )+ 64 ),"memset" ); 40return p ; 41} 42template < typename T > T * halloc (size_t n ) {// pinned, mapped; returns the device pointer 43void * h = nullptr ; 44void * d = nullptr ; 45ck (cudaHostAlloc (& h ,n * sizeof (T )+ 64 ,cudaHostAllocMapped ),"hostalloc" ); 46 std::memset (h ,0 ,n * sizeof (T )+ 64 ); 47ck (cudaHostGetDevicePointer (& d ,h ,0 ),"devptr" ); 48return (T * )d ; 49} 50 51struct Pools {// one K/V pool set of `pages` pages 52 k::KvHostPools p ;// reused as a plain pointer bundle 53void alloc (int64_t pages ,const k::QsaShapes & s ,int fmt ,bool host ) { 54const size_t rows = (size_t )pages * s .n_head_kv * s .page_size ; 55if (fmt == k::kKvHybrid ) { 56const size_t b = rows * k::kv_q4_bytes_per_head ((int )s .head_dim ); 57p .k_q = host ?halloc < int8_t > (rows * s .head_dim ) :dalloc < int8_t > (rows * s .head_dim ); 58p .k_scale = host ?halloc < uint16_t > (rows * 4 ) :dalloc < uint16_t > (rows * 4 ); 59p .v_q4 = host ?halloc < uint8_t > (b ) :dalloc < uint8_t > (b ); 60 }else if (fmt == k::kKvQ4 ) { 61const size_t b = rows * k::kv_q4_bytes_per_head ((int )s .head_dim ); 62p .k_q4 = host ?halloc < uint8_t > (b ) :dalloc < uint8_t > (b ); 63p .v_q4 = host ?halloc < uint8_t > (b ) :dalloc < uint8_t > (b ); 64 }else if (fmt == k::kKvInt8 ) { 65p .k_q = host ?halloc < int8_t > (rows * s .head_dim ) :dalloc < int8_t > (rows * s .head_dim ); 66p .v_q = host ?halloc < int8_t > (rows * s .head_dim ) :dalloc < int8_t > (rows * s .head_dim ); 67p .k_scale = host ?halloc < uint16_t > (rows * 4 ) :dalloc < uint16_t > (rows * 4 ); 68p .v_scale = host ?halloc < uint16_t > (rows * 4 ) :dalloc < uint16_t > (rows * 4 ); 69 }else { 70p .k_pool = host ?halloc < uint16_t > (rows * s .head_dim ) :dalloc < uint16_t > (rows * s .head_dim ); 71p .v_pool = host ?halloc < uint16_t > (rows * s .head_dim ) :dalloc < uint16_t > (rows * s .head_dim ); 72 } 73 } 74 k::QsaAttnPools attn (const int32_t * table )const { 75 k::QsaAttnPools a ; 76a .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 ; 77a .v_scale = p .v_scale ;a .k_q4 = p .k_q4 ;a .v_q4 = p .v_q4 ;a .page_table = table ; 78return a ; 79 } 80}; 81 82void append (const Pools & pl ,const int32_t * table ,const int32_t * step ,const float * kc ,const float * vc , 83const k::QsaShapes & s ,int fmt ,const k::KvHostPools * host ) { 84if (fmt == k::kKvHybrid ) {// exactly as qsa_layer: each half folded onto its own pool, host copy by halves 85const k::KvHostPools hk = host ? k::kv_hybrid_k_half (* host ) : k::KvHostPools {}, 86hv = host ? k::kv_hybrid_v_half (* host ) : k::KvHostPools {}; 87 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 , 88host ?& hk :nullptr ); 89 k::kv_append_q4_step (pl .p .v_q4 ,pl .p .v_q4 ,table ,step ,vc ,vc ,s ,nullptr ,host ?& hv :nullptr ); 90 }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 ); 91else 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 ); 92else k::kv_append_step (pl .p .k_pool ,pl .p .v_pool ,table ,step ,kc ,vc ,s ,nullptr ,host ); 93} 94 95// A selection like qsa_block_topk's: ascending cells, whole blocks, the tail block's cells, and one partial block. 96std::vector < int32_t > selection (int64_t n_kv ,int64_t width , std::mt19937 & rng ) { 97 std::vector < int32_t > ids ; 98if (n_kv <=width ) { 99for (int64_t c = 0 ;c < n_kv ;++ c )ids .push_back ((int32_t )c ); 100return ids ; 101 } 102const int64_t n_bid = n_kv /4 ,tail = n_kv - n_bid * 4 ; 103 std::set < int64_t > blocks ; 104const int64_t want_full = (width - tail ) /4 ,part = (width - tail ) %4 ; 105 std::uniform_int_distribution < int64_t > any (0 ,n_bid - 1 ),recent (std::max < int64_t > (0 ,n_bid - 2048 ),n_bid - 1 ); 106while ((int64_t )blocks .size ()< want_full + (part ?1 :0 ))blocks .insert (rng () %2 ?recent (rng ) :any (rng )); 107int64_t partial_block = part ?* std::next (blocks .begin (), (long ) (rng () %blocks .size ())) :-1 ; 108for (int64_t b :blocks ) { 109const int64_t take = b == partial_block ?part :4 ; 110for (int64_t i = 0 ;i < take ;++ i )ids .push_back ((int32_t ) (b * 4 + i )); 111 } 112for (int64_t c = n_bid * 4 ;c < n_kv ;++ c )ids .push_back ((int32_t )c ); 113 std::sort (ids .begin (),ids .end ()); 114return ids ; 115} 116 117bool run (int fmt ) { 118const char * name = fmt == k::kKvHybrid ?"k8v4" :fmt == k::kKvQ4 ?"q4_0" :fmt == k::kKvInt8 ?"int8" :"fp16" ; 119 k::QsaShapes s = k::qsa_real_shapes (); 120const int64_t N = 40000 ,n_blocks = (N + 3 ) /4 ,n_slots = 8 * 516 + 700 ;// must evict: slots < blocks 121const int64_t cap = k::qsa_selection_width (k::kTopkMaxCells ,s ),NQ = 8 ; 122const int64_t H = s .n_head_kv ,D = s .head_dim ,NH = s .n_head ; 123 std::mt19937 rng (7 + 4 * fmt ); 124 std::normal_distribution < float > nd (0.f ,1.f ); 125 126Pools ref ,slots ,host ; 127ref .alloc (n_blocks ,s ,fmt , false); 128slots .alloc (n_slots ,s ,fmt , false); 129host .alloc (n_blocks ,s ,fmt , true); 130int32_t * ident = dalloc < int32_t > (n_blocks ); 131 { 132 std::vector < int32_t > t (n_blocks ); 133for (int64_t i = 0 ;i < n_blocks ;++ i )t [i ]= (int32_t )i ; 134ck (cudaMemcpy (ident ,t .data (),n_blocks * 4 ,cudaMemcpyHostToDevice ),"ident" ); 135 } 136 k::KvStreamMap m ; 137m .page_table = dalloc < int32_t > (n_blocks ); 138m .slot_block = dalloc < int32_t > (n_slots );m .slot_stamp = dalloc < int32_t > (n_slots );m .slot_ref = dalloc < int32_t > (n_slots ); 139m .miss_block = dalloc < int32_t > (n_slots );m .miss_slot = dalloc < int32_t > (n_slots ); 140m .ctl = dalloc < int32_t > (k::kKvCtlInts ); 141m .n_blocks = n_blocks ;m .n_slots = n_slots ; 142 k::kv_stream_reset (m ,nullptr ); 143 144float * kc = dalloc < float > (H * D ); 145float * vc = dalloc < float > (H * D ); 146int32_t * step = dalloc < int32_t > (k::kStepCount ); 147int32_t * steps = dalloc < int32_t > (NQ * k::kStepCount ); 148int32_t * ids = dalloc < int32_t > (NQ * cap ); 149float * q = dalloc < float > (NQ * NH * D ); 150const uint64_t scr = k::qsa_decode_attn_scratch_floats (cap ,s ); 151float * scratch = dalloc < float > (NQ * scr ); 152float * out_ref = dalloc < float > (NQ * NH * D ); 153float * out_str = dalloc < float > (NQ * NH * D ); 154 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 ); 155 std::vector < int32_t > pt (n_blocks ),sb (n_slots ); 156 157int batches = 0 ,bad = 0 ; 158for (int64_t pos = 0 ;pos < N ;++ pos ) { 159for (auto & x :hk )x = nd (rng )* ((pos %17 == 0 ) ?30.f :1.f ); 160for (auto & x :hv )x = nd (rng ); 161const int32_t st [4 ]= {(int32_t )pos , (int32_t ) (pos + 1 ), (int32_t ) ((pos + 1 ) /4 ),0 }; 162ck (cudaMemcpy (kc ,hk .data (),hk .size ()* 4 ,cudaMemcpyHostToDevice ),"k" ); 163ck (cudaMemcpy (vc ,hv .data (),hv .size ()* 4 ,cudaMemcpyHostToDevice ),"v" ); 164ck (cudaMemcpy (step ,st ,sizeof (st ),cudaMemcpyHostToDevice ),"step" ); 165append (ref ,ident ,step ,kc ,vc ,s ,fmt ,nullptr ); 166append (slots ,m .page_table ,step ,kc ,vc ,s ,fmt ,& host .p ); 167if (pos %131 != 130 && pos != N - 1 )continue ; 168// a batch: n_q queries at the last n_q positions (as a verify window), each with its own selection 169const int n_q = 1 + (int ) (rng () %NQ ); 170 std::vector < int32_t > hids ((size_t )NQ * cap ,0 ),hst (NQ * 4 ,0 ); 171for (int t = 0 ;t < n_q ;++ t ) { 172const int64_t p = std::max < int64_t > (0 ,pos - (n_q - 1 - t )),n_kv = p + 1 ; 173const int64_t width = std::min < int64_t > (n_kv ,cap ); 174const std::vector < int32_t > sel = selection (n_kv ,width ,rng ); 175if ((int64_t )sel .size ()!= width ) { std::fprintf (stderr ,"selection size %zu != %lld\n" ,sel .size (), (long long )width );return false; } 176 std::copy (sel .begin (),sel .end (),hids .begin ()+ (size_t )t * cap ); 177hst [t * 4 + 0 ]= (int32_t )p ;hst [t * 4 + 1 ]= (int32_t )n_kv ;hst [t * 4 + 2 ]= (int32_t ) (n_kv /4 ); 178hst [t * 4 + 3 ]= (int32_t )width ; 179 } 180for (auto & x :hq )x = nd (rng ); 181ck (cudaMemcpy (ids ,hids .data (),hids .size ()* 4 ,cudaMemcpyHostToDevice ),"ids" ); 182ck (cudaMemcpy (steps ,hst .data (),hst .size ()* 4 ,cudaMemcpyHostToDevice ),"steps" ); 183ck (cudaMemcpy (q ,hq .data (),hq .size ()* 4 ,cudaMemcpyHostToDevice ),"q" ); 184 k::qsa_decode_attn_batch (q ,ref .attn (ident ),ids ,steps ,cap ,s ,scratch ,out_ref ,n_q ,nullptr ); 185 k::kv_stream_resolve (m ,slots .attn (m .page_table ),host .p ,fmt ,ids ,steps ,n_q ,cap ,s ,nullptr ); 186 k::qsa_decode_attn_batch (q ,slots .attn (m .page_table ),ids ,steps ,cap ,s ,scratch ,out_str ,n_q ,nullptr ); 187ck (cudaDeviceSynchronize (),"batch" ); 188ck (cudaMemcpy (a .data (),out_ref , (size_t )n_q * NH * D * 4 ,cudaMemcpyDeviceToHost ),"a" ); 189ck (cudaMemcpy (b2 .data (),out_str , (size_t )n_q * NH * D * 4 ,cudaMemcpyDeviceToHost ),"b" ); 190if (std::memcmp (a .data (),b2 .data (), (size_t )n_q * NH * D * 4 )!= 0 ) { 191if (bad ++ < 5 ) std::fprintf (stderr ," %s pos %lld n_q %d: streamed attention differs\n" ,name , (long long )pos ,n_q ); 192 } 193// the map inverts itself 194ck (cudaMemcpy (pt .data (),m .page_table ,n_blocks * 4 ,cudaMemcpyDeviceToHost ),"pt" ); 195ck (cudaMemcpy (sb .data (),m .slot_block ,n_slots * 4 ,cudaMemcpyDeviceToHost ),"sb" ); 196int64_t resident = 0 ; 197for (int64_t bk = 0 ;bk < n_blocks ;++ bk ) { 198if (pt [bk ]< -1 || pt [bk ] >=n_slots || (pt [bk ] >=0 && sb [pt [bk ]]!= bk )) { 199if (bad ++ < 5 ) std::fprintf (stderr ," map broken at block %lld (table %d)\n" , (long long )bk ,pt [bk ]); 200break ; 201 } 202resident += pt [bk ] >=0 ; 203 } 204for (int64_t sl = 0 ;sl < n_slots ;++ sl ) 205if (sb [sl ] >=0 && pt [sb [sl ]]!= sl ) {if (bad ++ < 5 ) std::fprintf (stderr ," slot %lld not in the table\n" , (long long )sl );break ; } 206++ batches ; 207 } 208const k::KvStreamCounters c = k::kv_stream_counters (m ); 209 std::printf (" %s: %d batches, %llu block lookups, %llu misses (%.1f%% hit), overflow %d, %d failures\n" , 210name ,batches , (unsigned long long )c .lookups , (unsigned long long )c .misses , 211c .lookups ?100.0 * (double ) (c .lookups - c .misses ) / (double )c .lookups :0.0 , (int )c .overflow ,bad ); 212if (c .overflow || c .calls != (uint64_t )batches || c .misses == 0 || c .misses >=c .lookups )++ bad ; 213 214// 4. a ring over the same host copy: blocks [b1 - R, b1) restored, read through `b % R` 215 { 216const int64_t R = 1500 ,b1 = n_blocks ,b0 = b1 - R ; 217Pools ring ; 218ring .alloc (R ,s ,fmt , false); 219int32_t * rt = dalloc < int32_t > (n_blocks ); 220 k::kv_ring_table (rt ,n_blocks ,R ,nullptr ); 221 k::kv_ring_restore (ring .attn (rt ),host .p ,fmt ,b0 ,b1 ,R ,s ,nullptr ); 222const int64_t width = cap ; 223 std::vector < int32_t > hids ((size_t )cap ),hst = {(int32_t ) (N - 1 ), (int32_t )N , (int32_t ) (N /4 ), (int32_t )width }; 224for (int64_t i = 0 ;i < width ;++ i )hids [i ]= (int32_t ) (N - width + i );// the window's last cells 225ck (cudaMemcpy (ids ,hids .data (),hids .size ()* 4 ,cudaMemcpyHostToDevice ),"ids" ); 226ck (cudaMemcpy (steps ,hst .data (),16 ,cudaMemcpyHostToDevice ),"steps" ); 227 k::qsa_decode_attn_batch (q ,ref .attn (ident ),ids ,steps ,cap ,s ,scratch ,out_ref ,1 ,nullptr ); 228 k::qsa_decode_attn_batch (q ,ring .attn (rt ),ids ,steps ,cap ,s ,scratch ,out_str ,1 ,nullptr ); 229ck (cudaDeviceSynchronize (),"ring" ); 230ck (cudaMemcpy (a .data (),out_ref , (size_t )NH * D * 4 ,cudaMemcpyDeviceToHost ),"a" ); 231ck (cudaMemcpy (b2 .data (),out_str , (size_t )NH * D * 4 ,cudaMemcpyDeviceToHost ),"b" ); 232const bool ok = std::memcmp (a .data (),b2 .data (), (size_t )NH * D * 4 )== 0 ; 233 std::printf (" %s ring restore: %s\n" ,name ,ok ?"identical" :"DIFFERS" ); 234if (!ok )++ bad ; 235 } 236return bad == 0 ; 237} 238}// namespace 239 240int main () { 241 std::printf ("kv_stream_parity: streamed vs resident KV, bitwise\n" ); 242const bool a = run (k::kKvInt8 ),b = run (k::kKvF16 ),c = run (k::kKvQ4 ),d = run (k::kKvHybrid ); 243if (!a || !b || !c || !d )++ g_fail ; 244 std::printf (g_fail ?"FAIL\n" :"PASS\n" ); 245return g_fail ?1 :0 ; 246}