okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
7e8485a48
main
1// src/kernels/kv_window_parity.cpp - the verify window's KV calls on a STREAMED layer, as the engine makes them (GPU, no model). 2// 3// kv_stream_parity appends one cell per call. The engine's verify window (and the MTP drafter's catch-up) appends n = 2..6 4// cells in ONE launch (kv_append_*_steps, a 3D grid with the host copy as a kernel argument), resolves the n selections 5// together, attends n queries in one batched launch, and does all of it inside a captured graph on a non-blocking 6// stream. This test drives exactly that sequence for each KV format on a layer that must evict, and on a ring over a host 7// copy (the drafter's layout), and checks 8// 1. the host copy equals a fully resident reference pool, byte for byte, for every cell written; 9// 2. every resident slot equals the reference block it holds (the slots never go stale); 10// 3. the streamed attention of each window equals the resident one, bitwise (n queries); 11// 4. the ring's attention (last cells, through `block % n_slots`) equals the resident one; 12// 5. nothing faulted (a stray store or load of the append / copy / attention kernels ends the run in a CUDA error). 13// Every window runs twice per format: as plain launches and replayed from a graph captured per window size. Issue #2403 14// (q4_0 KV + KV streaming + MTP) is the case this was written for. 15#include "strata/kernels/kv_q4.hpp" 16#include "strata/kernels/kv_q8.hpp" 17#include "strata/kernels/kv_stream.hpp" 18#include "strata/kernels/qsa.hpp" 19#include "strata/kernels/qsa_decode_attn.hpp" 20 21#include <cuda_runtime.h> 22 23#include <algorithm> 24#include <cstdio> 25#include <cstdlib> 26#include <cstring> 27#include <random> 28#include <set> 29#include <vector> 30 31namespace k= strata::kernels; 32 33namespace { 34void ck (cudaError_t e ,const char * w ) { 35if (e != cudaSuccess ) { std::fprintf (stderr ,"%s: %s\n" ,w ,cudaGetErrorString (e )); std::exit (2 ); } 36} 37template < typename T > T * 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} 43struct HostBuf {// pinned, mapped: `d` is what kernels get, `h` what the test reads 44void * h = nullptr ; 45void * d = nullptr ; 46}; 47HostBuf halloc (size_t bytes ) { 48HostBuf b ; 49ck (cudaHostAlloc (& b .h ,bytes + 64 ,cudaHostAllocMapped ),"hostalloc" ); 50 std::memset (b .h ,0 ,bytes + 64 ); 51ck (cudaHostGetDevicePointer (& b .d ,b .h ,0 ),"devptr" ); 52return b ; 53} 54 55constexpr int kMaxWin = 6 ;// --spec 4 windows are <= 5 tokens, the drafter's catch-up T <= 6 56 57// One KV array of a pool set: the pointer (device or host-mapped), the host-readable twin, bytes per page (block). 58struct Arr { 59void * d = nullptr ; 60void * h = nullptr ;// non-null for host copies 61size_t per_block = 0 ; 62}; 63 64struct Pools {// one pool set of `pages` pages in the layout of format `fmt` 65 k::KvHostPools p ; 66 std::vector < Arr > arrs ; 67void alloc (int64_t pages ,const k::QsaShapes & s ,int fmt ,bool host ) { 68const size_t rows_per_page = (size_t )s .n_head_kv * s .page_size ,rows = (size_t )pages * rows_per_page ; 69auto mk = [& ](size_t per_row ,auto ** field ) { 70using T = std::remove_pointer_t < std::remove_pointer_t < decltype(field )>> ; 71Arr a ; 72a .per_block = rows_per_page * per_row ; 73if (host ) {HostBuf b = halloc (rows * per_row );a .d = b .d ;a .h = b .h ; } 74else a .d = dalloc < uint8_t > (rows * per_row ); 75* field = (T * )a .d ; 76arrs .push_back (a ); 77 }; 78const size_t q4 = k::kv_q4_bytes_per_head ((int )s .head_dim ); 79const size_t codes = (size_t )s .head_dim ,scales = (size_t ) (s .head_dim / k::KV_Q8_GROUP )* 2 ; 80if (fmt == k::kKvHybrid ) { 81mk (codes ,& p .k_q );mk (scales ,& p .k_scale );mk (q4 ,& p .v_q4 ); 82 }else if (fmt == k::kKvQ4 ) { 83mk (q4 ,& p .k_q4 );mk (q4 ,& p .v_q4 ); 84 }else {// kKvInt8 85mk (codes ,& p .k_q );mk (codes ,& p .v_q );mk (scales ,& p .k_scale );mk (scales ,& p .v_scale ); 86 } 87 } 88 k::QsaAttnPools attn (const int32_t * table )const { 89 k::QsaAttnPools a ; 90a .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 ; 91a .v_scale = p .v_scale ;a .k_q4 = p .k_q4 ;a .v_q4 = p .v_q4 ;a .page_table = table ; 92return a ; 93 } 94}; 95 96// The appends of one window, as verify.cpp / mtp.cpp make them. 97void append_window (const Pools & pl ,const int32_t * table ,const int32_t * steps ,const float * kc ,const float * vc ,int n , 98const k::QsaShapes & s ,int fmt ,const k::KvHostPools * host ,cudaStream_t cs ) { 99const int cur = (int ) (s .n_head_kv * s .head_dim ); 100if (fmt == k::kKvHybrid ) {// the unused half's lanes folded onto the used pool (layer.cpp), the 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_steps (pl .p .k_q ,pl .p .k_q ,pl .p .k_scale ,pl .p .k_scale ,table ,steps , k::kStepCount ,kc ,kc ,cur ,n ,s ,cs , 104host ?& hk :nullptr ); 105 k::kv_append_q4_steps (pl .p .v_q4 ,pl .p .v_q4 ,table ,steps , k::kStepCount ,n ,vc ,vc ,s ,cs ,host ?& hv :nullptr ); 106 }else if (fmt == k::kKvQ4 ) { 107 k::kv_append_q4_steps (pl .p .k_q4 ,pl .p .v_q4 ,table ,steps , k::kStepCount ,n ,kc ,vc ,s ,cs ,host ); 108 }else { 109 k::kv_append_q8_steps (pl .p .k_q ,pl .p .v_q ,pl .p .k_scale ,pl .p .v_scale ,table ,steps , k::kStepCount ,kc ,vc ,cur ,n ,s ,cs , 110host ); 111 } 112} 113 114// A selection like qsa_block_topk's: ascending cells, whole blocks, the tail block's cells, and one partial block. 115std::vector < int32_t > selection (int64_t n_kv ,int64_t width , std::mt19937 & rng ) { 116 std::vector < int32_t > ids ; 117if (n_kv <=width ) { 118for (int64_t c = 0 ;c < n_kv ;++ c )ids .push_back ((int32_t )c ); 119return ids ; 120 } 121const int64_t n_bid = n_kv /4 ,tail = n_kv - n_bid * 4 ; 122 std::set < int64_t > blocks ; 123const int64_t want_full = (width - tail ) /4 ,part = (width - tail ) %4 ; 124 std::uniform_int_distribution < int64_t > any (0 ,n_bid - 1 ),recent (std::max < int64_t > (0 ,n_bid - 2048 ),n_bid - 1 ); 125while ((int64_t )blocks .size ()< want_full + (part ?1 :0 ))blocks .insert (rng () %2 ?recent (rng ) :any (rng )); 126int64_t partial_block = part ?* std::next (blocks .begin (), (long ) (rng () %blocks .size ())) :-1 ; 127for (int64_t b :blocks ) { 128const int64_t take = b == partial_block ?part :4 ; 129for (int64_t i = 0 ;i < take ;++ i )ids .push_back ((int32_t ) (b * 4 + i )); 130 } 131for (int64_t c = n_bid * 4 ;c < n_kv ;++ c )ids .push_back ((int32_t )c ); 132 std::sort (ids .begin (),ids .end ()); 133return ids ; 134} 135 136int g_bad = 0 ; 137void fail (const char * fmt_name ,const char * what ,long long a = 0 ,long long b = 0 ) { 138if (g_bad ++ < 12 ) std::fprintf (stderr ," FAIL %s: %s (%lld, %lld)\n" ,fmt_name ,what ,a ,b ); 139} 140 141bool run (int fmt ,bool graphs ) { 142const char * name = fmt == k::kKvHybrid ?"k8v4" :fmt == k::kKvQ4 ?"q4_0" :"int8" ; 143 k::QsaShapes s = k::qsa_real_shapes (); 144const int64_t N = 40000 ,n_blocks = (N + 3 ) /4 ; 145const int64_t cap = k::qsa_selection_width (k::kTopkMaxCells ,s ); 146const int64_t n_slots = kMaxWin * (cap /4 + 2 )+ 700 ;// holds one window's selections; far fewer than n_blocks 147const int64_t R = 1500 ;// the drafter-like ring 148const int64_t H = s .n_head_kv ,D = s .head_dim ,NH = s .n_head ; 149 std::mt19937 rng (11 + 5 * fmt + graphs ); 150 std::normal_distribution < float > nd (0.f ,1.f ); 151 152cudaStream_t cs ; 153ck (cudaStreamCreateWithFlags (& cs ,cudaStreamNonBlocking ),"stream" ); 154Pools ref ,slots ,host ,ring ,ring_host ; 155ref .alloc (n_blocks ,s ,fmt , false); 156slots .alloc (n_slots ,s ,fmt , false); 157host .alloc (n_blocks ,s ,fmt , true); 158ring .alloc (R ,s ,fmt , false); 159ring_host .alloc (n_blocks ,s ,fmt , true); 160int32_t * ident = dalloc < int32_t > (n_blocks ); 161int32_t * rtab = dalloc < int32_t > (n_blocks ); 162 { 163 std::vector < int32_t > t (n_blocks ); 164for (int64_t i = 0 ;i < n_blocks ;++ i )t [i ]= (int32_t )i ; 165ck (cudaMemcpy (ident ,t .data (),n_blocks * 4 ,cudaMemcpyHostToDevice ),"ident" ); 166 k::kv_ring_table (rtab ,n_blocks ,R ,nullptr ); 167 } 168 k::KvStreamMap m ; 169m .page_table = dalloc < int32_t > (n_blocks ); 170m .slot_block = dalloc < int32_t > (n_slots );m .slot_stamp = dalloc < int32_t > (n_slots );m .slot_ref = dalloc < int32_t > (n_slots ); 171m .miss_block = dalloc < int32_t > (n_slots );m .miss_slot = dalloc < int32_t > (n_slots ); 172m .ctl = dalloc < int32_t > (k::kKvCtlInts ); 173m .n_blocks = n_blocks ;m .n_slots = n_slots ; 174 k::kv_stream_reset (m ,nullptr ); 175ck (cudaDeviceSynchronize (),"setup" ); 176 177float * kc = dalloc < float > (kMaxWin * H * D ); 178float * vc = dalloc < float > (kMaxWin * H * D ); 179int32_t * steps = dalloc < int32_t > (kMaxWin * k::kStepCount ); 180int32_t * ids = dalloc < int32_t > (kMaxWin * cap ); 181int32_t * ring_ids = dalloc < int32_t > (cap ); 182int32_t * ring_step = dalloc < int32_t > (k::kStepCount ); 183float * q = dalloc < float > (kMaxWin * NH * D ); 184const uint64_t scr = k::qsa_decode_attn_scratch_floats (cap ,s ); 185float * scratch = dalloc < float > (kMaxWin * scr ); 186float * out_ref = dalloc < float > (kMaxWin * NH * D ); 187float * out_str = dalloc < float > (kMaxWin * NH * D ); 188float * scratch2 = dalloc < float > (scr ); 189float * out_rref = dalloc < float > (NH * D ); 190float * out_rng = dalloc < float > (NH * D ); 191const k::KvHostPools * hp = & host .p ; 192const k::KvHostPools * rhp = & ring_host .p ; 193 194// per window size n: the appends (resident reference, streamed + host copy, ring + its host copy) and, for a window 195// that is also attended, the streamed resolve + attention, each captured once 196cudaGraphExec_t g_app [kMaxWin + 1 ]= {},g_att [kMaxWin + 1 ]= {}; 197auto record_app = [& ](int n ) { 198append_window (ref ,ident ,steps ,kc ,vc ,n ,s ,fmt ,nullptr ,cs ); 199append_window (slots ,m .page_table ,steps ,kc ,vc ,n ,s ,fmt ,hp ,cs ); 200append_window (ring ,rtab ,steps ,kc ,vc ,n ,s ,fmt ,rhp ,cs ); 201 }; 202auto record_att = [& ](int n ) { 203 k::kv_stream_resolve (m ,slots .attn (m .page_table ),host .p ,fmt ,ids ,steps ,n ,cap ,s ,cs ); 204 k::qsa_decode_attn_batch (q ,slots .attn (m .page_table ),ids ,steps ,cap ,s ,scratch ,out_str ,n ,cs ); 205 }; 206if (graphs ) { 207for (int n = 1 ;n <=kMaxWin ;++ n ) { 208cudaGraph_t g = nullptr ; 209ck (cudaStreamBeginCapture (cs ,cudaStreamCaptureModeThreadLocal ),"begin capture" ); 210record_app (n ); 211ck (cudaStreamEndCapture (cs ,& g ),"end capture" ); 212ck (cudaGraphInstantiate (& g_app [n ],g ,0 ),"instantiate append" ); 213 (void )cudaGraphDestroy (g ); 214ck (cudaStreamBeginCapture (cs ,cudaStreamCaptureModeThreadLocal ),"begin capture" ); 215record_att (n ); 216ck (cudaStreamEndCapture (cs ,& g ),"end capture" ); 217ck (cudaGraphInstantiate (& g_att [n ],g ,0 ),"instantiate attention" ); 218 (void )cudaGraphDestroy (g ); 219 } 220 } 221 222 std::vector < float > hk (kMaxWin * H * D ),hv (kMaxWin * H * D ),hq (kMaxWin * NH * D ); 223 std::vector < float > a ((size_t )kMaxWin * NH * D ),b2 ((size_t )kMaxWin * NH * D ); 224int windows = 0 ,attended = 0 ; 225int64_t pos = 0 ; 226while (pos < N ) { 227const int n = (int ) std::min < int64_t > (N - pos ,1 + (int64_t ) (rng () %kMaxWin )); 228for (int j = 0 ;j < n ;++ j ) 229for (int64_t i = 0 ;i < H * D ;++ i ) { 230hk [j * H * D + i ]= nd (rng )* (((pos + j ) %17 == 0 ) ?30.f :1.f ); 231hv [j * H * D + i ]= nd (rng ); 232 } 233 std::vector < int32_t > st ((size_t )n * k::kStepCount ); 234for (int j = 0 ;j < n ;++ j ) { 235const int64_t p = pos + j ; 236st [j * 4 + k::kStepPos ]= (int32_t )p ;st [j * 4 + k::kStepNKv ]= (int32_t ) (p + 1 ); 237st [j * 4 + k::kStepNBid ]= (int32_t ) ((p + 1 ) /4 );st [j * 4 + k::kStepWidth ]= (int32_t ) std::min < int64_t > (p + 1 ,cap ); 238 } 239ck (cudaMemcpyAsync (kc ,hk .data (), (size_t )n * H * D * 4 ,cudaMemcpyHostToDevice ,cs ),"k" ); 240ck (cudaMemcpyAsync (vc ,hv .data (), (size_t )n * H * D * 4 ,cudaMemcpyHostToDevice ,cs ),"v" ); 241ck (cudaMemcpyAsync (steps ,st .data (),st .size ()* 4 ,cudaMemcpyHostToDevice ,cs ),"steps" ); 242ck (cudaStreamSynchronize (cs ),"upload" );// pageable sources: the copies above must be done before the vectors change 243if (graphs )ck (cudaGraphLaunch (g_app [n ],cs ),"graph append" ); 244else record_app (n ); 245++ windows ; 246pos += n ; 247if (windows %37 != 0 && pos < N )continue ; 248// attend the window just appended: n queries at its n positions, each with a selection of its own 249 std::vector < int32_t > hids ((size_t )n * cap ,0 ); 250for (int j = 0 ;j < n ;++ j ) { 251const int64_t n_kv = pos - (n - 1 - j ),width = std::min < int64_t > (n_kv ,cap ); 252const std::vector < int32_t > sel = selection (n_kv ,width ,rng ); 253if ((int64_t )sel .size ()!= width ) { std::fprintf (stderr ,"selection size\n" ); std::exit (2 ); } 254 std::copy (sel .begin (),sel .end (),hids .begin ()+ (size_t )j * cap ); 255 } 256for (auto & x :hq )x = nd (rng ); 257ck (cudaMemcpyAsync (ids ,hids .data (),hids .size ()* 4 ,cudaMemcpyHostToDevice ,cs ),"ids" ); 258ck (cudaMemcpyAsync (q ,hq .data (), (size_t )n * NH * D * 4 ,cudaMemcpyHostToDevice ,cs ),"q" ); 259ck (cudaStreamSynchronize (cs ),"upload2" ); 260 k::qsa_decode_attn_batch (q ,ref .attn (ident ),ids ,steps ,cap ,s ,scratch ,out_ref ,n ,cs ); 261if (graphs )ck (cudaGraphLaunch (g_att [n ],cs ),"graph attention" ); 262else record_att (n ); 263// the ring: the last cells of the last query, through block % R (the drafter reads its window only) 264 { 265const int64_t n_kv = pos ,width = std::min < int64_t > (n_kv ,cap ); 266 std::vector < int32_t > rid ((size_t )cap ,0 ); 267for (int64_t i = 0 ;i < width ;++ i )rid [i ]= (int32_t ) (n_kv - width + i ); 268const int32_t rs [4 ]= {(int32_t ) (n_kv - 1 ), (int32_t )n_kv , (int32_t ) (n_kv /4 ), (int32_t )width }; 269ck (cudaMemcpyAsync (ring_ids ,rid .data (),rid .size ()* 4 ,cudaMemcpyHostToDevice ,cs ),"rid" ); 270ck (cudaMemcpyAsync (ring_step ,rs ,sizeof (rs ),cudaMemcpyHostToDevice ,cs ),"rs" ); 271ck (cudaStreamSynchronize (cs ),"upload3" ); 272 k::qsa_decode_attn_batch (q ,ref .attn (ident ),ring_ids ,ring_step ,cap ,s ,scratch2 ,out_rref ,1 ,cs ); 273 k::qsa_decode_attn_batch (q ,ring .attn (rtab ),ring_ids ,ring_step ,cap ,s ,scratch2 ,out_rng ,1 ,cs ); 274 } 275ck (cudaStreamSynchronize (cs ),"window" ); 276ck (cudaGetLastError (),"window (last error)" ); 277// 3. the streamed attention of the n queries equals the resident one 278ck (cudaMemcpy (a .data (),out_ref , (size_t )n * NH * D * 4 ,cudaMemcpyDeviceToHost ),"a" ); 279ck (cudaMemcpy (b2 .data (),out_str , (size_t )n * NH * D * 4 ,cudaMemcpyDeviceToHost ),"b" ); 280if (std::memcmp (a .data (),b2 .data (), (size_t )n * NH * D * 4 )!= 0 )fail (name ,"streamed attention differs" ,pos ,n ); 281// 4. the ring reads the same values as the resident pool 282 std::vector < float > r (NH * D ),rr (NH * D ); 283ck (cudaMemcpy (r .data (),out_rng , (size_t )NH * D * 4 ,cudaMemcpyDeviceToHost ),"r" ); 284ck (cudaMemcpy (rr .data (),out_rref , (size_t )NH * D * 4 ,cudaMemcpyDeviceToHost ),"rr" ); 285if (std::memcmp (rr .data (),r .data (), (size_t )NH * D * 4 )!= 0 )fail (name ,"ring attention differs" ,pos ,n ); 286++ attended ; 287 } 288// 1. the host copies equal the resident reference, byte for byte (all cells written) 289long long host_bad = 0 ,slot_bad = 0 ,resident = 0 ; 290for (int ai = 0 ;ai < (int )ref .arrs .size ();++ ai ) { 291const size_t per = ref .arrs [ai ].per_block ; 292 std::vector < uint8_t > rb ((size_t )n_blocks * per ); 293ck (cudaMemcpy (rb .data (),ref .arrs [ai ].d ,rb .size (),cudaMemcpyDeviceToHost ),"ref d2h" ); 294const size_t written = (size_t ) ((N + 3 ) /4 )* per ; 295host_bad += std::memcmp (rb .data (),host .arrs [ai ].h ,written )!= 0 ; 296host_bad += std::memcmp (rb .data (),ring_host .arrs [ai ].h ,written )!= 0 ; 297// 2. every resident slot equals the block it holds 298 std::vector < uint8_t > sb ((size_t )n_slots * per ); 299ck (cudaMemcpy (sb .data (),slots .arrs [ai ].d ,sb .size (),cudaMemcpyDeviceToHost ),"slots d2h" ); 300 std::vector < int32_t > pt (n_blocks ); 301ck (cudaMemcpy (pt .data (),m .page_table ,n_blocks * 4 ,cudaMemcpyDeviceToHost ),"pt" ); 302for (int64_t bk = 0 ;bk < n_blocks ;++ bk ) 303if (pt [bk ] >=0 ) { 304if (ai == 0 )++ resident ; 305slot_bad += std::memcmp (sb .data ()+ (size_t )pt [bk ]* per ,rb .data ()+ (size_t )bk * per ,per )!= 0 ; 306 } 307 } 308if (host_bad )fail (name ,"a host copy differs from the resident reference" ,host_bad ); 309if (slot_bad )fail (name ,"a resident slot differs from its block" ,slot_bad ); 310const k::KvStreamCounters c = k::kv_stream_counters (m ); 311 std::printf (" %-5s %-6s: %d windows (%d attended), %llu block lookups, %llu misses, %lld resident, overflow %d, host/ring-host bad %lld, stale slots %lld\n" , 312name ,graphs ?"graph" :"direct" ,windows ,attended , (unsigned long long )c .lookups , (unsigned long long )c .misses , 313resident , (int )c .overflow ,host_bad ,slot_bad ); 314if (c .overflow || c .misses == 0 || c .misses >=c .lookups )fail (name ,"the stream counters are off" , (long long )c .misses , (long long )c .lookups ); 315for (int n = 1 ;n <=kMaxWin ;++ n ) { 316if (g_app [n ]) (void )cudaGraphExecDestroy (g_app [n ]); 317if (g_att [n ]) (void )cudaGraphExecDestroy (g_att [n ]); 318 } 319 (void )cudaStreamDestroy (cs ); 320return g_bad == 0 ; 321} 322}// namespace 323 324int main () { 325 std::printf ("kv_window_parity: verify-window KV calls on a streamed layer and on a ring, plain launches and graph replays\n" ); 326bool ok = true; 327for (int fmt : {k::kKvQ4 , k::kKvInt8 , k::kKvHybrid }) 328for (bool graphs : {false, true})ok = run (fmt ,graphs )&& ok ; 329 std::printf (ok && g_bad == 0 ?"PASS\n" :"FAIL\n" ); 330return ok && g_bad == 0 ?0 :1 ; 331}