okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
7c5e84612
main
1#include <cstring> 2// src/kernels/qsa_select_bench.cpp - the prompt path's QSA selection (qsa_select.hpp) timed per stage, block scores 3// (the warp kernel and the fast one: tensor cores, or the FP32 tiled kernel on CUDA below sm_80) and top-k, for a batch of consecutive queries at a given context, and 4// the two scorers compared: score difference and how many selections differ (GPU, synthetic, no model). 5// Usage: qsa_select_bench [context=131072] [queries=256] [reps=10] [capacity_cells] 6// capacity_cells (the engine's --max-context): the score buffers and the top-k dispatch follow the CAPACITY 7// (max_blocks = capacity / 4 + 2), the work follows the context. Default: capacity = context (max_blocks = ctx / 4 + 1). 8#include "strata/kernels/qsa.hpp" 9#include "strata/kernels/qsa_select.hpp" 10 11#include <cuda_runtime.h> 12 13#include <algorithm> 14#include <cmath> 15#include <cstdio> 16#include <cstdlib> 17#include <cstring> 18#include <random> 19#include <vector> 20 21namespace k= strata::kernels; 22 23namespace { 24void ck (cudaError_t e ,const char * w ) { 25if (e != cudaSuccess ) { std::fprintf (stderr ,"%s: %s\n" ,w ,cudaGetErrorString (e )); std::exit (2 ); } 26} 27template < typename T > T * up (const std::vector < T >& h ) { 28T * d = nullptr ; 29ck (cudaMalloc (& d ,h .size ()* sizeof (T )+ 64 ),"malloc" ); 30ck (cudaMemcpy (d ,h .data (),h .size ()* sizeof (T ),cudaMemcpyHostToDevice ),"upload" ); 31return d ; 32} 33}// namespace 34 35int main (int argc ,char ** argv ) { 36const int64_t ctx = argc > 1 ? std::atoll (argv [1 ]) :131072 ; 37const int64_t nq = argc > 2 ? std::atoll (argv [2 ]) :256 ; 38const int reps = argc > 3 ? std::atoi (argv [3 ]) :10 ; 39const k::QsaShapes s = k::qsa_real_shapes (); 40const int64_t capacity = argc > 4 ? std::atoll (argv [4 ]) :0 ; 41const int64_t max_blocks = capacity > 0 ?capacity /4 + 2 :ctx /4 + 1 ,cap = k::qsa_selection_width (k::kTopkMaxCells ,s ); 42 std::mt19937 rng (7 ); 43 std::normal_distribution < float > nd (0.f ,1.f ); 44// keys with a shared direction plus noise, so the scores have a spread like a real indexer's 45 std::vector < float > dir (128 ),pooled ((size_t ) (max_blocks * 128 )),dead (128 ),q ((size_t ) (nq * 512 )); 46for (auto & x :dir )x = nd (rng ); 47for (int64_t b = 0 ;b < max_blocks ;++ b ) { 48const float a = nd (rng ); 49for (int d = 0 ;d < 128 ;++ d )pooled [(size_t ) (b * 128 + d )]= 0.5f * a * dir [d ]+ nd (rng ); 50 } 51for (auto & x :dead )x = nd (rng ); 52for (int64_t i = 0 ;i < nq ;++ i ) 53for (int d = 0 ;d < 512 ;++ d )q [(size_t ) (i * 512 + d )]= 0.2f * dir [d %128 ]+ 0.1f * nd (rng ); 54 std::vector < int32_t > steps ((size_t ) (nq * k::kStepCount )); 55for (int64_t i = 0 ;i < nq ;++ i ) {// qsa_step_fill's arithmetic (kept here so the bench links only qsa_select) 56int32_t * st = steps .data ()+ i * k::kStepCount ; 57const int64_t pos = ctx - nq + i ; 58st [k::kStepPos ]= (int32_t )pos ; 59st [k::kStepNKv ]= (int32_t ) (pos + 1 ); 60st [k::kStepNBid ]= (int32_t ) ((pos + 1 ) /s .idx_block ); 61st [k::kStepWidth ]= (int32_t ) k::qsa_selection_width (pos + 1 ,s ); 62 } 63const float * d_pooled = up (pooled ); 64const float * d_dead = up (dead ); 65const float * d_q = up (q ); 66const int32_t * d_steps = up (steps ); 67float * sc_old = nullptr ,* sc_new = nullptr ; 68int32_t * ids_old = nullptr ,* ids_new = nullptr ; 69ck (cudaMalloc (& sc_old , (size_t ) (nq * max_blocks )* 4 ),"malloc" ); 70ck (cudaMalloc (& sc_new , (size_t ) (nq * max_blocks )* 4 ),"malloc" ); 71ck (cudaMalloc (& ids_old , (size_t ) (nq * cap )* 4 ),"malloc" ); 72ck (cudaMalloc (& ids_new , (size_t ) (nq * cap )* 4 ),"malloc" ); 73const int64_t active = steps [(size_t ) ((nq - 1 )* k::kStepCount + k::kStepNBid )]+ 1 ; 74if (std::getenv ("QSA_BENCH_DECODE" )) {// a decode window's call: no block count (block_scores_multi_kernel) 75auto run_dec = [& ] { k::qsa_block_scores (d_pooled ,d_dead ,d_q ,d_steps ,nq ,max_blocks ,s ,sc_old ,nullptr ,-1 ); }; 76run_dec (); 77ck (cudaDeviceSynchronize (),"sync" ); 78cudaEvent_t a0 ,a1 ; 79cudaEventCreate (& a0 );cudaEventCreate (& a1 ); 80cudaEventRecord (a0 ); 81for (int r = 0 ;r < reps ;++ r )run_dec (); 82cudaEventRecord (a1 );cudaEventSynchronize (a1 ); 83float ms = 0 ;cudaEventElapsedTime (& ms ,a0 ,a1 ); 84 std::vector < float > h ((size_t ) (nq * max_blocks )); 85ck (cudaMemcpy (h .data (),sc_old ,h .size ()* 4 ,cudaMemcpyDeviceToHost ),"down" ); 86unsigned long long x = 1469598103934665603ull ; 87for (int64_t i = 0 ;i < nq ;++ i ) { 88const int64_t nbid = steps [(size_t ) (i * k::kStepCount + k::kStepNBid )]; 89for (int64_t j = 0 ;j <=nbid ;++ j ) {uint32_t u ; std::memcpy (& u ,& h [(size_t ) (i * max_blocks + j )],4 );x = (x ^u )* 1099511628211ull ; } 90 } 91const double gb = (double )active * 512.0 /1e9 ; 92 std::printf ("decode scores ctx %lld, %lld queries: %.1f us (%.0f GB/s of pooled keys), hash %016llx\n" , (long long )ctx , 93 (long long )nq ,1e3 * ms /reps ,gb / (ms /reps /1e3 ),x ); 94return 0 ; 95 } 96auto run_old = [& ] { k::qsa_block_scores (d_pooled ,d_dead ,d_q ,d_steps ,nq ,max_blocks ,s ,sc_old ,nullptr ,active ); }; 97// a device without the tensor-core scorer (HIP other than gfx12): time the warp scorer and the top-k only 98const bool have_tc = k::qsa_block_scores_tc (d_pooled ,d_dead ,d_q ,d_steps ,1 ,max_blocks ,s ,sc_new ,nullptr ,active ); 99auto run_new = [& ] { 100if (!k::qsa_block_scores_tc (d_pooled ,d_dead ,d_q ,d_steps ,nq ,max_blocks ,s ,sc_new ,nullptr ,active )) { 101 std::fprintf (stderr ,"tc scorer refused\n" ); 102 std::exit (2 ); 103 } 104 }; 105run_old (); 106if (have_tc )run_new (); 107else ck (cudaMemcpy (sc_new ,sc_old , (size_t ) (nq * max_blocks )* 4 ,cudaMemcpyDeviceToDevice ),"copy" ); 108 k::qsa_block_topk_ref (sc_old ,d_steps ,nq ,max_blocks ,cap ,s ,ids_old ,nullptr ); 109 k::qsa_block_topk (sc_new ,d_steps ,nq ,max_blocks ,cap ,s ,ids_new ,nullptr ,active ); 110int32_t * ids_reg = nullptr ;// the register top-k on the OLD scores: must equal the reference exactly 111ck (cudaMalloc (& ids_reg , (size_t ) (nq * cap )* 4 ),"malloc" ); 112 k::qsa_block_topk (sc_old ,d_steps ,nq ,max_blocks ,cap ,s ,ids_reg ,nullptr ,active ); 113ck (cudaDeviceSynchronize (),"warm" ); 114// compare 115 std::vector < float > a ((size_t ) (nq * max_blocks )),b (a .size ()); 116 std::vector < int32_t > ia ((size_t ) (nq * cap )),ib (ia .size ()); 117ck (cudaMemcpy (a .data (),sc_old ,a .size ()* 4 ,cudaMemcpyDeviceToHost ),"down" ); 118ck (cudaMemcpy (b .data (),sc_new ,b .size ()* 4 ,cudaMemcpyDeviceToHost ),"down" ); 119if (std::getenv ("QSA_BENCH_HASH" )) {// the fast scorer's bytes (compare STRATA_SELECT_SIMT=1 and =2) 120unsigned long long h = 1469598103934665603ull ; 121for (int64_t i = 0 ;i < nq ;++ i ) { 122const int64_t nbid = steps [(size_t ) (i * k::kStepCount + k::kStepNBid )]; 123for (int64_t j = 0 ;j < nbid ;++ j ) { 124uint32_t u ; 125 std::memcpy (& u ,& b [(size_t ) (i * max_blocks + j )],4 ); 126h = (h ^u )* 1099511628211ull ; 127 } 128 } 129 std::printf ("fast scores hash %016llx\n" ,h ); 130 } 131ck (cudaMemcpy (ia .data (),ids_old ,ia .size ()* 4 ,cudaMemcpyDeviceToHost ),"down" ); 132ck (cudaMemcpy (ib .data (),ids_new ,ib .size ()* 4 ,cudaMemcpyDeviceToHost ),"down" ); 133 std::vector < int32_t > ir (ia .size ()); 134ck (cudaMemcpy (ir .data (),ids_reg ,ir .size ()* 4 ,cudaMemcpyDeviceToHost ),"down" ); 135int64_t reg_same = 0 ; 136for (int64_t i = 0 ;i < nq ;++ i ) { 137const int64_t w = steps [(size_t ) (i * k::kStepCount + k::kStepWidth )]; 138reg_same += std::equal (ia .begin ()+ i * cap ,ia .begin ()+ i * cap + w ,ir .begin ()+ i * cap ); 139 } 140double max_rel = 0 ,sum_rel = 0 ,n_rel = 0 ; 141int64_t same_sel = 0 ,cells_diff = 0 ,cells_all = 0 ; 142for (int64_t i = 0 ;i < nq ;++ i ) { 143const int32_t * st = steps .data ()+ i * k::kStepCount ; 144for (int64_t j = 0 ;j <=st [k::kStepNBid ];++ j ) { 145const double x = a [(size_t ) (i * max_blocks + j )],y = b [(size_t ) (i * max_blocks + j )]; 146const double r = std::fabs (x - y ) / std::max (1e-6 , std::fabs (x )); 147max_rel = std::max (max_rel ,r ); 148sum_rel += r ; 149n_rel += 1 ; 150 } 151const int64_t w = st [k::kStepWidth ]; 152 std::vector < int32_t > x (ia .begin ()+ i * cap ,ia .begin ()+ i * cap + w ),y (ib .begin ()+ i * cap ,ib .begin ()+ i * cap + w ); 153same_sel += x == y ; 154 std::vector < int32_t > d ; 155 std::set_symmetric_difference (x .begin (),x .end (),y .begin (),y .end (), std::back_inserter (d )); 156cells_diff += (int64_t )d .size () /2 ; 157cells_all += w ; 158 } 159// accuracy against an FP64 host reference on a sample (blocks below n_bid; the tail block is the warp kernel's own 160// arithmetic in both scorers). Gate, as the prompt-attention harness's: the scorer under test is no worse than 4x 161// the warp kernel's error, floored at 1e-5 of the score scale. The floor is the fast scorer's own: measured against the FP64 162// reference it sits at 1.0e-6 of the scale (RTX 5070 sm_120, ctx 32K: 0.99e-6, which a 1e-6 floor failed by rounding; 131K: 0.97e-6) 163// against the warp kernel's 7e-8, i.e. FP32-accumulated TF32-split products; 1e-5 keeps ten times that margin and is still 164// two orders below a plain single-TF32 product (~1e-3), which is the error this gate exists to catch. 165double err_old = 0 ,err_new = 0 ,scale = 0 ; 166 { 167 std::mt19937 srng (11 ); 168const int64_t nqs = std::min < int64_t > (nq ,32 ); 169for (int64_t qs = 0 ;qs < nqs ;++ qs ) { 170const int64_t i = qs * nq /nqs ; 171const int64_t nbid = steps [(size_t ) (i * k::kStepCount + k::kStepNBid )]; 172if (nbid <=0 )continue ; 173for (int sidx = 0 ;sidx < 1024 ;++ sidx ) { 174const int64_t j = sidx < 64 ? std::min < int64_t > (nbid - 1 ,sidx ) : (int64_t ) (srng () % (uint64_t )nbid ); 175double ref = 0 ; 176for (int h = 0 ;h < 4 ;++ h ) { 177double d = 0 ; 178for (int c = 0 ;c < 128 ;++ c )d += (double )q [(size_t ) (i * 512 + h * 128 + c )]* (double )pooled [(size_t ) (j * 128 + c )]; 179ref += d > 0 ?d :0 ; 180 } 181scale = std::max (scale , std::fabs (ref )); 182err_old = std::max (err_old , std::fabs (ref - (double )a [(size_t ) (i * max_blocks + j )])); 183err_new = std::max (err_new , std::fabs (ref - (double )b [(size_t ) (i * max_blocks + j )])); 184 } 185 } 186 } 187const bool acc_ok = !have_tc || err_new <= std::max (4.0 * err_old ,1e-5 * scale ); 188// time 189cudaEvent_t e0 ,e1 ; 190cudaEventCreate (& e0 );cudaEventCreate (& e1 ); 191auto timed = [& ](auto f ) { 192cudaEventRecord (e0 ); 193for (int r = 0 ;r < reps ;++ r )f (); 194cudaEventRecord (e1 ); 195ck (cudaEventSynchronize (e1 ),"time" ); 196float ms = 0 ; 197cudaEventElapsedTime (& ms ,e0 ,e1 ); 198return ms /reps ; 199 }; 200const float t_old = timed (run_old ),t_new = have_tc ?timed (run_new ) :t_old ; 201const float t_tk = timed ([& ] { k::qsa_block_topk_ref (sc_old ,d_steps ,nq ,max_blocks ,cap ,s ,ids_old ,nullptr ); }); 202const float t_tk2 = timed ([& ] { k::qsa_block_topk (sc_old ,d_steps ,nq ,max_blocks ,cap ,s ,ids_reg ,nullptr ,active ); }); 203 std::printf ("top-k %.3f -> %.3f ms (%.1fx), register top-k identical to the reference %lld/%lld\n" ,t_tk ,t_tk2 , 204t_tk /t_tk2 , (long long )reg_same , (long long )nq ); 205 std::printf ("%s accuracy vs FP64 (score scale %.3g): warp kernel max err %.3g, fast scorer max err %.3g (%.2g of scale)\n" , 206 !have_tc ?"SKIP" :acc_ok ?"PASS" :"FAIL" ,scale ,err_old ,err_new ,scale > 0 ?err_new /scale :0.0 ); 207if (!have_tc ) std::printf ("fast scorer not available on this device: warp scorer %.3f ms, top-k %.3f ms (%.0f%% of the two)\n" ,t_old ,t_tk2 ,100.0 * t_tk2 / (t_old + t_tk2 )); 208 std::printf ("ctx %lld, %lld queries x %lld blocks: scores %.3f -> %.3f ms (%.1fx), top-k %.3f ms; score rel diff " 209"mean %.2g max %.2g; selections identical %lld/%lld, cells differing %.4f%%\n" , (long long )ctx , 210 (long long )nq , (long long )active ,t_old ,t_new ,t_old /t_new ,t_tk ,sum_rel / std::max (1.0 ,n_rel ), 211max_rel , (long long )same_sel , (long long )nq ,cells_all ?100.0 * (double )cells_diff / (double )cells_all :0.0 ); 212return acc_ok && reg_same == nq ?0 :1 ; 213}