okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
7c5e84612
main
1// src/kernels/qsa_rows_bench.cpp - QSAROWS (docs/QSAROWS.md): what the T rows of a verification window cost in a QSA 2// layer's decode kernels at a long context, row by row. GPU, synthetic data at the real geometry (24 query heads x 3// 256, 2 KV heads, indexer 4 x 128, blocks of 4 cells, top-k 2048), INT8 pools, no model. 4// 5// The hypothesis under test: "the decode attention of the QSA layers works row by row, re-reading K/V for every row of 6// the window, so 8 layers x ~0.25 ms explain the ~2.5 ms a row the stage costs". The kernels measured here are the 7// ones verify.cpp launches for a window of T rows at the usual long-context options (--max-context 262144, --kv int8): 8// 9// scores qsa_block_scores (block_scores_multi_kernel: every pooled key read ONCE for the T queries) 10// topk qsa_block_topk (one CTA per query; max_blocks 65538 -> block_topk_wide_kernel) 11// attn qsa_decode_attn_batch over each row's own selection, cap 2051 (33 chunks x 2 KV heads x T blocks) 12// append native_qsa_indexer_append_steps for the T raw indexer keys (one CTA, the steps in sequence) 13// dense qsa_decode_attn_batch over a 32768-cell window per row: the drafter's shape, which the hypothesis's 14// "~240 us a query" comes from (the drafter runs it with ONE query per step: capture_round's record_rest) 15// 16// --rows: block_scores_rows_kernel (STRATA_QSA_ROWS=1, docs/QSAROWS.md) against the multi kernel, scores and ids bit for 17// bit, and its microseconds beside the reference's. 18// 19// qsa_rows_bench [--device N] [--iters 100] [--ctx 131072] [--max-context 262144] [--rows] [--no-dense] 20// exit 0 (77: no GPU; 1: a --rows parity failure) 21#include "strata/kernels/kv_q8.hpp" 22#include "strata/kernels/native_qsa_indexer.hpp" 23#include "strata/kernels/qsa.hpp" 24#include "strata/kernels/qsa_decode_attn.hpp" 25#include "strata/kernels/qsa_select.hpp" 26#include "strata/kernels/rope_scaling.hpp" 27 28#include <cuda_runtime.h> 29 30#include <algorithm> 31#include <cmath> 32#include <cstdint> 33#include <cstdio> 34#include <cstdlib> 35#include <cstring> 36#include <random> 37#include <set> 38#include <string> 39#include <vector> 40 41namespace k= strata::kernels; 42 43namespace { 44cudaStream_t st = nullptr ; 45void ck (cudaError_t e ,const char * what ) { 46if (e != cudaSuccess ) { 47 std::fprintf (stderr ,"qsa_rows_bench: %s: %s\n" ,what ,cudaGetErrorString (e )); 48 std::exit (2 ); 49 } 50} 51template < typename T > T * dalloc (size_t n ) { 52T * p = nullptr ; 53ck (cudaMalloc ((void ** )& p ,n * sizeof (T )+ 256 ),"cudaMalloc" ); 54ck (cudaMemset (p ,0 ,n * sizeof (T )+ 256 ),"cudaMemset" ); 55return p ; 56} 57template < typename T > T * upload (const std::vector < T >& h ) { 58T * d = dalloc < T > (h .size ()); 59ck (cudaMemcpy (d ,h .data (),h .size ()* sizeof (T ),cudaMemcpyHostToDevice ),"upload" ); 60return d ; 61} 62template < typename T > std::vector < T > download (const T * d ,size_t n ) { 63 std::vector < T > h (n ); 64ck (cudaMemcpy (h .data (),d ,n * sizeof (T ),cudaMemcpyDeviceToHost ),"download" ); 65return h ; 66} 67uint16_t f16_scale_q8 (uint32_t r ) {return (uint16_t ) ((9u <<10 ) | (r & 0x3FFu )); } 68 69struct Timer { 70cudaEvent_t e0 = nullptr ,e1 = nullptr ; 71Timer () {ck (cudaEventCreate (& e0 ),"event" );ck (cudaEventCreate (& e1 ),"event" ); } 72 ~Timer () {cudaEventDestroy (e0 );cudaEventDestroy (e1 ); } 73// microseconds per call over `iters` back-to-back calls, warmed; the median of three such runs 74template < typename F > double us (F && f ,int iters ) { 75double r [3 ]; 76for (int a = 0 ;a < 3 ;++ a ) { 77for (int i = 0 ;i < 4 ;++ i )f (); 78ck (cudaDeviceSynchronize (),"warm" ); 79ck (cudaEventRecord (e0 ,st ),"record" ); 80for (int i = 0 ;i < iters ;++ i )f (); 81ck (cudaEventRecord (e1 ,st ),"record" ); 82ck (cudaEventSynchronize (e1 ),"sync" ); 83float ms = 0.0f ; 84ck (cudaEventElapsedTime (& ms ,e0 ,e1 ),"elapsed" ); 85r [a ]= 1000.0 * ms /iters ; 86 } 87 std::sort (r ,r + 3 ); 88return r [1 ]; 89 } 90}; 91 92constexpr int NH = 24 ,HD = 256 ,NKV = 2 ,IQ = 4 ,ID = 128 ; 93constexpr int MAXT = 4 ; 94 95struct Table {// us[T] for T = 1..MAXT 96double us [MAXT + 1 ]= {}; 97void const char * what )const { 98 std::printf (" %-44s" ,what ); 99for (int T = 1 ;T <=MAXT ;++ T ) std::printf (" T=%d %8.1f" ,T ,us [T ]); 100 std::printf (" | +%.1f us a row\n" , (us [MAXT ]- us [1 ]) / (MAXT - 1 )); 101 } 102}; 103}// namespace 104 105int main (int argc ,char ** argv ) { 106int device = 0 ,iters = 100 ; 107int64_t ctx = 131072 ,max_ctx = 262144 ; 108bool rows = false,dense = true; 109for (int i = 1 ;i < argc ;++ i ) { 110if (std::strcmp (argv [i ],"--device" )== 0 && i + 1 < argc )device = std::atoi (argv [++ i ]); 111else if (std::strcmp (argv [i ],"--iters" )== 0 && i + 1 < argc )iters = std::atoi (argv [++ i ]); 112else if (std::strcmp (argv [i ],"--ctx" )== 0 && i + 1 < argc )ctx = std::atoll (argv [++ i ]); 113else if (std::strcmp (argv [i ],"--max-context" )== 0 && i + 1 < argc )max_ctx = std::atoll (argv [++ i ]); 114else if (std::strcmp (argv [i ],"--rows" )== 0 )rows = true; 115else if (std::strcmp (argv [i ],"--no-dense" )== 0 )dense = false; 116else { 117 std::fprintf (stderr ,"usage: qsa_rows_bench [--device N] [--iters 100] [--ctx 131072] [--max-context 262144] " 118"[--rows] [--no-dense]\n" ); 119return 2 ; 120 } 121 } 122int devices = 0 ; 123if (cudaGetDeviceCount (& devices )!= cudaSuccess || devices == 0 ) { 124 std::puts ("SKIP: no GPU" ); 125return 77 ; 126 } 127ck (cudaSetDevice (device ),"cudaSetDevice" ); 128ck (cudaStreamCreate (& st ),"stream" ); 129cudaDeviceProp prop {}; 130ck (cudaGetDeviceProperties (& prop ,device ),"cudaGetDeviceProperties" ); 131const k::QsaShapes s = k::qsa_real_shapes (); 132const int64_t PS = s .page_size ; 133const int64_t max_cells = (max_ctx + PS - 1 ) /PS * PS ; 134const int64_t max_blocks = max_cells /s .idx_block + 2 ;// verify.cpp: max_blocks_ 135const int64_t cap = k::qsa_selection_width (k::kTopkMaxCells ,s );// verify.cpp: cap_ (2051) 136const int64_t cells = (ctx + MAXT + 64 + PS - 1 ) /PS * PS ;// the pools' rows: resident cells 137const int64_t pages = cells /PS ,prows = pages * NKV * PS ; 138const int64_t dense_win = 32768 ,dense_cap = dense_win ;// the drafter's --mtp-window 139 std::printf ("qsa_rows_bench on device %d (%s, %d.%d), %d iterations: context %lld, capacity %lld cells (max_blocks " 140"%lld), selection cap %lld, int8 pools over %lld cells%s\n" , 141device ,prop .name ,prop .major ,prop .minor ,iters , (long long )ctx , (long long )max_cells , 142 (long long )max_blocks , (long long )cap , (long long )cells , 143 std::getenv ("STRATA_QSA_ROWS" ) ?", STRATA_QSA_ROWS set" :"" ); 144 std::mt19937 rng (20261012u ); 145 std::normal_distribution < float > nd (0.0f ,1.0f ); 146 147// ---- INT8 K/V pools, every page resident, identity page table 148 std::vector < int8_t > c8 ((size_t ) (prows * HD )); 149for (auto & x :c8 )x = (int8_t ) ((int ) (rng () %255u )- 127 ); 150int8_t * k8 = upload (c8 ); 151for (auto & x :c8 )x = (int8_t ) ((int ) (rng () %255u )- 127 ); 152int8_t * v8 = upload (c8 ); 153c8 .clear ();c8 .shrink_to_fit (); 154 std::vector < uint16_t > sc ((size_t ) (prows * (HD / k::KV_Q8_GROUP ))); 155for (auto & x :sc )x = f16_scale_q8 (rng ()); 156uint16_t * k8s = upload (sc ); 157for (auto & x :sc )x = f16_scale_q8 (rng ()); 158uint16_t * v8s = upload (sc ); 159 std::vector < int32_t > tab ((size_t )pages ); 160for (int64_t i = 0 ;i < pages ;++ i )tab [(size_t )i ]= (int32_t )i ; 161int32_t * table = upload (tab ); 162 k::QsaAttnPools pools ; 163pools .page_table = table ; 164pools .k_q = k8 ;pools .v_q = v8 ;pools .k_scale = k8s ;pools .v_scale = v8s ; 165 166// ---- the indexer's state: pooled keys (unit-ish rows), the spare, a tail, the block position 167 std::vector < float > hp ((size_t ) (max_blocks * ID )); 168for (auto & x :hp )x = nd (rng )* 0.09f ; 169float * pooled = upload (hp ); 170hp .clear ();hp .shrink_to_fit (); 171 std::vector < float > hd ((size_t )ID ); 172for (auto & x :hd )x = nd (rng )* 0.09f ; 173float * dead = upload (hd ); 174float * tail = dalloc < float > ((size_t ) (s .idx_block - 1 )* ID ); 175int32_t * block_pos = dalloc < int32_t > (1 ); 176 std::vector < float > hg ((size_t )ID ,1.0f ); 177float * gamma = upload (hg ); 178// the T rows' indexer queries: one query perturbed a little per row, so the selections overlap as a window's do 179 std::vector < float > hq0 ((size_t ) (IQ * ID )),hqi ((size_t ) (MAXT * IQ * ID )); 180for (auto & x :hq0 )x = nd (rng ); 181for (int t = 0 ;t < MAXT ;++ t ) 182for (int i = 0 ;i < IQ * ID ;++ i )hqi [(size_t )t * IQ * ID + i ]= hq0 [(size_t )i ]+ 0.15f * nd (rng ); 183float * q_idx = upload (hqi ); 184 std::vector < float > hraw ((size_t ) (MAXT * ID )); 185for (auto & x :hraw )x = nd (rng ); 186float * raw = upload (hraw ); 187// the attention queries [MAXT, NH, HD] 188 std::vector < float > hq ((size_t ) (MAXT * NH * HD )); 189for (auto & x :hq )x = nd (rng ); 190float * q = upload (hq ); 191// step records for rows 0..MAXT-1 at cells ctx .. ctx + MAXT - 1 (verify: pos, n_kv, n_bid, width) 192 std::vector < int32_t > hst ((size_t ) (MAXT * k::kStepCount )); 193for (int t = 0 ;t < MAXT ;++ t ) { 194const int64_t pos = ctx + t ,n_kv = pos + 1 ; 195hst [(size_t )t * k::kStepCount + k::kStepPos ]= (int32_t )pos ; 196hst [(size_t )t * k::kStepCount + k::kStepNKv ]= (int32_t )n_kv ; 197hst [(size_t )t * k::kStepCount + k::kStepNBid ]= (int32_t ) (n_kv /s .idx_block ); 198hst [(size_t )t * k::kStepCount + k::kStepWidth ]= (int32_t ) k::qsa_selection_width (n_kv ,s ); 199 } 200int32_t * steps = upload (hst ); 201// the drafter's dense window: the same cells, width = the window 202 std::vector < int32_t > hsd (hst ); 203for (int t = 0 ;t < MAXT ;++ t )hsd [(size_t )t * k::kStepCount + k::kStepWidth ]= (int32_t )dense_win ; 204int32_t * steps_d = upload (hsd ); 205 std::vector < int32_t > hwid ((size_t ) (MAXT * dense_cap )); 206for (int t = 0 ;t < MAXT ;++ t ) 207for (int64_t j = 0 ;j < dense_win ;++ j )hwid [(size_t )t * dense_cap + j ]= (int32_t ) (ctx + t + 1 - dense_win + j ); 208int32_t * ids_d = upload (hwid ); 209hwid .clear ();hwid .shrink_to_fit (); 210 211float * scores = dalloc < float > ((size_t ) (MAXT * max_blocks )); 212int32_t * ids = dalloc < int32_t > ((size_t ) (MAXT * cap )); 213const size_t scr_floats = (size_t ) k::qsa_decode_attn_scratch_floats (cap ,s ); 214float * scratch = dalloc < float > (scr_floats * MAXT ); 215float * attn = dalloc < float > ((size_t ) (MAXT * NH * HD )); 216const size_t scr_floats_d = (size_t ) k::qsa_decode_attn_scratch_floats (dense_cap ,s ); 217float * scratch_d = dalloc < float > (scr_floats_d * MAXT ); 218float * attn_d = dalloc < float > ((size_t ) (MAXT * NH * HD )); 219const k::QsaIndexerBuffers ib {tail ,dead ,pooled ,block_pos }; 220const k::RopeScaling scaling ; 221 222// ---- the selections once (the attention's inputs), and how much the rows' selections overlap 223 k::qsa_block_scores (pooled ,dead ,q_idx ,steps ,MAXT ,max_blocks ,s ,scores ,st ); 224 k::qsa_block_topk (scores ,steps ,MAXT ,max_blocks ,cap ,s ,ids ,st ); 225ck (cudaDeviceSynchronize (),"selection" ); 226 { 227const std::vector < int32_t > hid = download (ids , (size_t ) (MAXT * cap )); 228 std::printf (" selections: width %d a row;" ,hst [k::kStepWidth ]); 229for (int T = 2 ;T <=MAXT ;++ T ) { 230 std::set < int32_t > u ; 231for (int t = 0 ;t < T ;++ t ) 232for (int j = 0 ;j < hst [(size_t )t * k::kStepCount + k::kStepWidth ];++ j )u .insert (hid [(size_t )t * cap + j ]); 233 std::printf (" union of %d rows %zu cells (%.2fx one row)" ,T ,u .size (), (double )u .size () /hst [k::kStepWidth ]); 234 } 235 std::puts ("" ); 236 } 237 238Timer tm ; 239Table t_scores ,t_topk ,t_attn ,t_append ,t_layer ,t_dense ; 240for (int T = 1 ;T <=MAXT ;++ T ) { 241t_scores .us [T ]= tm .us ([& ] { k::qsa_block_scores (pooled ,dead ,q_idx ,steps ,T ,max_blocks ,s ,scores ,st ); },iters ); 242t_topk .us [T ]= tm .us ([& ] { k::qsa_block_topk (scores ,steps ,T ,max_blocks ,cap ,s ,ids ,st ); },iters ); 243t_attn .us [T ]= tm .us ([& ] { k::qsa_decode_attn_batch (q ,pools ,ids ,steps ,cap ,s ,scratch ,attn ,T ,st ); },iters ); 244// the append writes the tail / pooled / block_pos the scores read; its own cells (ctx .. ctx + T - 1) land in 245// the tail (ctx % 4 == 0) and, at T == 4, complete block ctx / 4: the same state every call 246t_append .us [T ]= tm .us ([& ] { 247 k::native_qsa_indexer_append_steps (raw ,steps + k::kStepPos , (int ) k::kStepCount ,T ,0 ,gamma ,1e-6f ,ib ,s , 248max_cells ,scaling ,st ); 249 },iters ); 250t_layer .us [T ]= tm .us ([& ] { 251 k::native_qsa_indexer_append_steps (raw ,steps + k::kStepPos , (int ) k::kStepCount ,T ,0 ,gamma ,1e-6f ,ib ,s , 252max_cells ,scaling ,st ); 253 k::qsa_block_scores (pooled ,dead ,q_idx ,steps ,T ,max_blocks ,s ,scores ,st ); 254 k::qsa_block_topk (scores ,steps ,T ,max_blocks ,cap ,s ,ids ,st ); 255 k::qsa_decode_attn_batch (q ,pools ,ids ,steps ,cap ,s ,scratch ,attn ,T ,st ); 256 },iters ); 257if (dense ) 258t_dense .us [T ]= tm .us ([& ] { 259 k::qsa_decode_attn_batch (q ,pools ,ids_d ,steps_d ,dense_cap ,s ,scratch_d ,attn_d ,T ,st ); 260 },iters ); 261 } 262 std::puts ("-- a QSA layer's decode kernels at the verification window's shape (us a call, median of 3 runs)" ); 263t_scores ."scores qsa_block_scores (multi)" ); 264t_topk ."topk qsa_block_topk" ); 265t_attn ."attn qsa_decode_attn_batch cap 2051" ); 266t_append ."append native_qsa_indexer_append_steps" ); 267t_layer ."layer append + scores + topk + attn" ); 268if (dense ) { 269 std::puts ("-- the drafter's dense window (32768 cells a row): the shape the hypothesis's ~240 us a query comes from" ); 270t_dense ."dense qsa_decode_attn_batch cap 32768" ); 271 } 272const double per_row = (t_layer .us [MAXT ]- t_layer .us [1 ]) / (MAXT - 1 ); 273 std::printf ("-- per row: %.1f us a QSA layer -> x4 layers (stage 0) %.2f ms, x8 layers (stage 1) %.2f ms\n" ,per_row , 2744 * per_row /1000.0 ,8 * per_row /1000.0 ); 275 276bool ok = true; 277if (rows ) { 278// QSAROWS: block_scores_rows_kernel (STRATA_QSA_ROWS=1) against block_scores_multi_kernel, bit for bit on the scores 279// and on the ids the top-k draws from them, at every T; then the microseconds of the two 280 std::puts ("-- STRATA_QSA_ROWS: qsa_block_scores_rows against qsa_block_scores (multi), scores and ids bit for bit" ); 281float * scores_b = dalloc < float > ((size_t ) (MAXT * max_blocks )); 282int32_t * ids_b = dalloc < int32_t > ((size_t ) (MAXT * cap )); 283long long cases = 0 ,failed = 0 ; 284Table t_rows ; 285for (int T = 1 ;T <=MAXT ;++ T ) { 286ck (cudaMemset (scores ,0xFF , (size_t )MAXT * max_blocks * 4 ),"fill" ); 287ck (cudaMemset (scores_b ,0xFF , (size_t )MAXT * max_blocks * 4 ),"fill" ); 288ck (cudaMemset (ids ,0x7F , (size_t )MAXT * cap * 4 ),"fill" ); 289ck (cudaMemset (ids_b ,0x7F , (size_t )MAXT * cap * 4 ),"fill" ); 290 k::qsa_block_scores (pooled ,dead ,q_idx ,steps ,T ,max_blocks ,s ,scores ,st ); 291if (!k::qsa_block_scores_rows (pooled ,dead ,q_idx ,steps ,T ,max_blocks ,s ,scores_b ,st )) { 292 std::printf (" FAIL T=%d: qsa_block_scores_rows refused the call\n" ,T ); 293++ cases ;++ failed ; 294continue ; 295 } 296 k::qsa_block_topk (scores ,steps ,T ,max_blocks ,cap ,s ,ids ,st ); 297 k::qsa_block_topk (scores_b ,steps ,T ,max_blocks ,cap ,s ,ids_b ,st ); 298ck (cudaDeviceSynchronize (),"rows sync" ); 299const std::vector < float > a = download (scores , (size_t )T * max_blocks ),b = download (scores_b , (size_t )T * max_blocks ); 300const std::vector < int32_t > ia = download (ids , (size_t )T * cap ),ib2 = download (ids_b , (size_t )T * cap ); 301++ cases ; 302const bool same_s = std::memcmp (a .data (),b .data (),a .size ()* 4 )== 0 ; 303const bool same_i = std::memcmp (ia .data (),ib2 .data (),ia .size ()* 4 )== 0 ; 304if (!same_s || !same_i ) { 305++ failed ; 306size_t count = 0 ,first = a .size (); 307for (size_t i = 0 ;i < a .size ();++ i ) 308if (std::memcmp (& a [i ],& b [i ],4 )!= 0 ) {if (first == a .size ())first = i ;++ count ; } 309 std::printf (" FAIL T=%d: scores %s (%zu of %zu differ, first at query %zu block %zu), ids %s\n" ,T , 310same_s ?"same" :"DIFFER" ,count ,a .size (),first / (size_t )max_blocks ,first % (size_t )max_blocks , 311same_i ?"same" :"DIFFER" ); 312 } 313t_rows .us [T ]= tm .us ([& ] { k::qsa_block_scores_rows (pooled ,dead ,q_idx ,steps ,T ,max_blocks ,s ,scores_b ,st ); }, 314iters ); 315 } 316// a short context too (n_bid small, the tail block with cells): rows at cells 100..103 317 { 318 std::vector < int32_t > hs2 (hst ); 319for (int t = 0 ;t < MAXT ;++ t ) { 320const int64_t pos = 100 + t ,n_kv = pos + 1 ; 321hs2 [(size_t )t * k::kStepCount + k::kStepPos ]= (int32_t )pos ; 322hs2 [(size_t )t * k::kStepCount + k::kStepNKv ]= (int32_t )n_kv ; 323hs2 [(size_t )t * k::kStepCount + k::kStepNBid ]= (int32_t ) (n_kv /s .idx_block ); 324hs2 [(size_t )t * k::kStepCount + k::kStepWidth ]= (int32_t ) k::qsa_selection_width (n_kv ,s ); 325 } 326int32_t * steps2 = upload (hs2 ); 327for (int T = 1 ;T <=MAXT ;++ T ) { 328ck (cudaMemset (scores ,0xFF , (size_t )MAXT * max_blocks * 4 ),"fill" ); 329ck (cudaMemset (scores_b ,0xFF , (size_t )MAXT * max_blocks * 4 ),"fill" ); 330 k::qsa_block_scores (pooled ,dead ,q_idx ,steps2 ,T ,max_blocks ,s ,scores ,st ); 331 k::qsa_block_scores_rows (pooled ,dead ,q_idx ,steps2 ,T ,max_blocks ,s ,scores_b ,st ); 332ck (cudaDeviceSynchronize (),"rows sync" ); 333const std::vector < float > a = download (scores , (size_t )T * max_blocks ),b = download (scores_b , (size_t )T * max_blocks ); 334++ cases ; 335if (std::memcmp (a .data (),b .data (),a .size ()* 4 )!= 0 ) {++ failed ; std::printf (" FAIL short context T=%d\n" ,T ); } 336 } 337ck (cudaFree (steps2 ),"free" ); 338 } 339 std::printf (" parity: %lld cases, %lld differ -> %s\n" ,cases ,failed ,failed ?"FAIL" :"bit-identical" ); 340ok = failed == 0 ; 341t_scores ."scores qsa_block_scores (multi, reference)" ); 342t_rows ."scores qsa_block_scores_rows" ); 343ck (cudaFree (scores_b ),"free" ); 344ck (cudaFree (ids_b ),"free" ); 345 } 346for (void * p : {(void * )k8 , (void * )v8 , (void * )k8s , (void * )v8s , (void * )table , (void * )pooled , (void * )dead , 347 (void * )tail , (void * )block_pos , (void * )gamma , (void * )q_idx , (void * )raw , (void * )q , (void * )steps , 348 (void * )steps_d , (void * )ids_d , (void * )scores , (void * )ids , (void * )scratch , (void * )attn , 349 (void * )scratch_d , (void * )attn_d }) 350ck (cudaFree (p ),"free" ); 351 std::printf ("qsa_rows_bench: %s\n" ,ok ?"done" :"FAIL" ); 352return ok ?0 :1 ; 353}