okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
386f9959f
main
1// STRATA_SELECT_TWO_PASS (qsa_two_pass.hpp) against today's prompt scorer, GPU, synthetic, no model: for prompt 2// chunks of 256 queries at depths from 2K to 256K and several kinds of keys (normal, indexer-like, wide magnitudes, 3// small integers with exact ties, near-duplicate and duplicate keys), qsa_block_topk over the two-pass row must return 4// exactly the ids it returns over qsa_block_scores_tc's row, every scored-again block must hold today's score bit for 5// bit, and every kept single-pass score must lie inside its bound (qsa_two_pass_check's counters). Then, for the 6// larger cases, the time of each scorer (one synthetic run, not a benchmark). Needs CUDA sm_80+ (77 = skipped 7// otherwise, and on HIP). 8#include "strata/kernels/qsa.hpp" 9#include "strata/kernels/qsa_select.hpp" 10#include "strata/kernels/qsa_two_pass.hpp" 11 12#include <cuda_runtime.h> 13 14#include <algorithm> 15#include <cmath> 16#include <cstdint> 17#include <cstdio> 18#include <cstdlib> 19#include <cstring> 20#include <random> 21#include <vector> 22 23namespace k= strata::kernels; 24namespace tp= strata::kernels::two_pass; 25 26namespace { 27void ck (cudaError_t e ) { 28if (e != cudaSuccess ) { 29 std::fprintf (stderr ,"CUDA: %s\n" ,cudaGetErrorString (e )); 30 std::exit (2 ); 31 } 32} 33 34enum Kind {kNormal ,kIndexer ,kWide ,kSmall ,kNear ,kDup ,kKinds }; 35const char * kKindName [kKinds ]= {"normal" ,"indexer-like" ,"wide magnitudes" ,"small integers" ,"near-duplicate keys" , 36"duplicate keys" }; 37 38struct Case {int64_t ctx ,queries ;Kind kind ;bool time ; }; 39 40// stride: the score row's stride in blocks; 0 = the case's own (ctx / 4 + 2), else the engine's (--max-context 262144: 41// 65,538, so qsa_block_topk takes the engine's dispatch on this card) 42bool run (const Case & c ,int64_t stride ) { 43const auto s = k::qsa_real_shapes (); 44const int64_t D = s .idx_dim ,H = s .idx_n_head ,own = c .ctx /s .idx_block + 2 ; 45const int64_t max_blocks = stride > own ?stride :own ; 46const int64_t nq = c .queries ,nq_cap = 256 ,cap = k::qsa_selection_width (k::kTopkMaxCells ,s ); 47 std::mt19937 rng (77001 + (unsigned )c .ctx + 13 * (unsigned )c .queries + 1009 * (unsigned )c .kind ); 48 std::normal_distribution < float > nd (0.f ,1.f ); 49 std::uniform_int_distribution < int > small (-3 ,3 ),expo (-16 ,16 ),coin (0 ,9 ); 50 std::vector < float > pooled ((size_t ) (max_blocks * D )),dead ((size_t )D ),q ((size_t ) (nq * H * D )); 51auto unit = [& ](float * v ,int n ,float norm ) { 52double ss = 0 ; 53for (int i = 0 ;i < n ;++ i )ss += (double )v [i ]* v [i ]; 54const float f = ss > 0 ? (float ) (norm / std::sqrt (ss )) :0.f ; 55for (int i = 0 ;i < n ;++ i )v [i ] *=f ; 56 }; 57for (int64_t b = 0 ;b < max_blocks ;++ b ) { 58float * kb = pooled .data ()+ b * D ; 59if (c .kind == kIndexer ) {// the mean of 4 RMS-normed cell keys, as the indexer pools them 60for (int i = 0 ;i < D ;++ i )kb [i ]= 0.f ; 61for (int cell = 0 ;cell < 4 ;++ cell ) { 62float ck_ [128 ]; 63for (int i = 0 ;i < D ;++ i )ck_ [i ]= nd (rng ); 64unit (ck_ , (int )D , std::sqrt ((float )D )); 65for (int i = 0 ;i < D ;++ i )kb [i ]+= 0.25f * ck_ [i ]; 66 } 67 }else if (c .kind == kNear && b > 0 && coin (rng )< 5 ) {// half the keys a hair from the one before 68for (int i = 0 ;i < D ;++ i )kb [i ]= kb [i - D ]* (1.0f + 1e-6f * nd (rng )); 69 }else if (c .kind == kDup && b >=8 && coin (rng )< 5 ) {// half the keys copies of an earlier one: exact ties 70const int64_t src = (int64_t ) (rng () % (uint32_t )b ); 71 std::memcpy (kb ,pooled .data ()+ src * D , (size_t )D * 4 ); 72 }else { 73for (int i = 0 ;i < D ;++ i ) { 74if (c .kind == kWide )kb [i ]= coin (rng )== 0 ?0.f : std::ldexp (nd (rng ),expo (rng )); 75else if (c .kind == kSmall )kb [i ]= (float )small (rng ); 76else kb [i ]= nd (rng ); 77 } 78 } 79 } 80for (auto & v :dead )v = nd (rng ); 81for (int64_t i = 0 ;i < nq ;++ i ) 82for (int64_t h = 0 ;h < H ;++ h ) { 83float * qh = q .data ()+ (i * H + h )* D ; 84if (c .kind == kIndexer ) {// RMS-normed, leaning towards a few keys (a peaked score row) 85for (int j = 0 ;j < D ;++ j )qh [j ]= nd (rng ); 86for (int r = 0 ;r < 3 ;++ r ) { 87const float * kb = pooled .data ()+ (int64_t ) (rng () % (uint32_t ) (max_blocks - 2 ))* D ; 88for (int j = 0 ;j < D ;++ j )qh [j ]+= 0.5f * kb [j ]; 89 } 90unit (qh , (int )D , std::sqrt ((float )D )); 91 }else { 92for (int j = 0 ;j < D ;++ j ) { 93if (c .kind == kWide )qh [j ]= coin (rng )== 0 ?0.f : std::ldexp (nd (rng ),expo (rng )); 94else if (c .kind == kSmall )qh [j ]= (float )small (rng ); 95else qh [j ]= nd (rng ); 96 } 97 } 98 } 99 std::vector < int32_t > steps ((size_t ) (nq * k::kStepCount )); 100for (int64_t i = 0 ;i < nq ;++ i ) { 101int32_t * st = steps .data ()+ i * k::kStepCount ; 102const int64_t pos = c .ctx - nq + i ; 103st [k::kStepPos ]= (int32_t )pos ; 104st [k::kStepNKv ]= (int32_t ) (pos + 1 ); 105st [k::kStepNBid ]= (int32_t ) ((pos + 1 ) /s .idx_block ); 106st [k::kStepWidth ]= (int32_t ) k::qsa_selection_width (pos + 1 ,s ); 107 } 108const int64_t last_nbid = steps [(size_t ) ((nq - 1 )* k::kStepCount + k::kStepNBid )],active = last_nbid + 1 ; 109float * dp ,* dd ,* dq ,* ref ,* two ; 110int32_t * dt ,* ref_ids ,* two_ids ; 111void * scratch ; 112const uint64_t sbytes = k::qsa_two_pass_scratch_bytes (nq_cap ,max_blocks ); 113const size_t n_sc = (size_t ) (nq * max_blocks ),n_id = (size_t ) (nq * cap ); 114ck (cudaMalloc (& dp ,pooled .size ()* 4 ));ck (cudaMalloc (& dd ,dead .size ()* 4 ));ck (cudaMalloc (& dq ,q .size ()* 4 )); 115ck (cudaMalloc (& dt ,steps .size ()* 4 ));ck (cudaMalloc (& ref ,n_sc * 4 ));ck (cudaMalloc (& two ,n_sc * 4 )); 116ck (cudaMalloc (& ref_ids ,n_id * 4 ));ck (cudaMalloc (& two_ids ,n_id * 4 ));ck (cudaMalloc (& scratch ,sbytes )); 117ck (cudaMemcpy (dp ,pooled .data (),pooled .size ()* 4 ,cudaMemcpyHostToDevice )); 118ck (cudaMemcpy (dd ,dead .data (),dead .size ()* 4 ,cudaMemcpyHostToDevice )); 119ck (cudaMemcpy (dq ,q .data (),q .size ()* 4 ,cudaMemcpyHostToDevice )); 120ck (cudaMemcpy (dt ,steps .data (),steps .size ()* 4 ,cudaMemcpyHostToDevice )); 121ck (cudaMemset (ref ,0x7f ,n_sc * 4 ));ck (cudaMemset (two ,0x3e ,n_sc * 4 )); 122ck (cudaMemset (ref_ids ,0xff ,n_id * 4 ));ck (cudaMemset (two_ids ,0xee ,n_id * 4 )); 123if (!k::qsa_block_scores_tc (dp ,dd ,dq ,dt ,nq ,max_blocks ,s ,ref ,nullptr ,active )) { 124 std::puts ("SKIP: no tensor-core scorer on this card" ); 125 std::exit (77 ); 126 } 127 k::qsa_block_topk (ref ,dt ,nq ,max_blocks ,cap ,s ,ref_ids ,nullptr ,active ); 128unsigned long long st0 [tp::kStatCount ]; 129 k::qsa_two_pass_stats (st0 , true,nullptr );// zero the counters 130if (!k::qsa_two_pass_keys (dp ,last_nbid ,nq_cap ,max_blocks ,scratch ,sbytes ,nullptr )|| 131 !k::qsa_block_scores_two_pass (dp ,dd ,dq ,dt ,nq ,nq_cap ,max_blocks ,s ,two ,scratch ,sbytes ,nullptr ,active )) { 132 std::fprintf (stderr ,"FAIL: the two-pass scorer did not run (ctx %lld)\n" , (long long )c .ctx ); 133return false; 134 } 135 k::qsa_block_topk (two ,dt ,nq ,max_blocks ,cap ,s ,two_ids ,nullptr ,active ); 136 k::qsa_two_pass_check (two ,two_ids ,ref ,ref_ids ,dt ,nq ,nq_cap ,max_blocks ,cap ,scratch ,nullptr ); 137ck (cudaDeviceSynchronize ()); 138unsigned long long st [tp::kStatCount ]; 139if (!k::qsa_two_pass_stats (st , true,nullptr )) { std::fprintf (stderr ,"FAIL: counters\n" );return false; } 140// the ids on the host too, every entry qsa_block_topk wrote 141 std::vector < int32_t > a (n_id ),b (n_id ); 142ck (cudaMemcpy (a .data (),ref_ids ,n_id * 4 ,cudaMemcpyDeviceToHost )); 143ck (cudaMemcpy (b .data (),two_ids ,n_id * 4 ,cudaMemcpyDeviceToHost )); 144int64_t bad_q = 0 ,compared = 0 ; 145for (int64_t i = 0 ;i < nq ;++ i ) { 146const int64_t n_kv = steps [(size_t ) (i * k::kStepCount + k::kStepNKv )]; 147const int64_t w = std::min < int64_t > (n_kv ,steps [(size_t ) (i * k::kStepCount + k::kStepWidth )]); 148compared += w ; 149if (!std::equal (a .begin ()+ i * cap ,a .begin ()+ i * cap + w ,b .begin ()+ i * cap ))++ bad_q ; 150 } 151const bool ok = bad_q == 0 && st [tp::kChkIdQueries ]== 0 && st [tp::kChkRescoredDiff ]== 0 && st [tp::kChkKeptOut ]== 0 && 152st [tp::kChkQueries ]== (unsigned long long )nq ; 153float ratio ; 154const uint32_t rb = (uint32_t )st [tp::kChkRatioMax ]; 155 std::memcpy (& ratio ,& rb ,4 ); 156const unsigned long long kept = st [tp::kStQueries ]- st [tp::kStFull ]; 157 std::printf ("%s ctx=%7lld stride=%5lld queries=%3lld %-20s: ids %lld queries differ (%lld ids compared); scored " 158"again %llu (%.1f per query), %llu of %llu scored-again blocks not bitwise; flagged %llu (%llu tiles in " 159"full); kept %llu, outside the bound %llu, max |S1-S3|/eps %.4f\n" , 160ok ?"ok " :"FAIL" , (long long )c .ctx , (long long )max_blocks , (long long )nq ,kKindName [c .kind ], 161 (long long )bad_q , (long long )compared ,st [tp::kStBand ],kept ? (double )st [tp::kStBand ] /kept :0.0 , 162st [tp::kChkRescoredDiff ],st [tp::kChkRescored ],st [tp::kStFull ],st [tp::kStFullTiles ],st [tp::kChkKept ], 163st [tp::kChkKeptOut ], (double )ratio ); 164if (ok && c .time && stride > 0 ) {// one synthetic observation of each scorer (the bench worker measures the engine) 165cudaEvent_t e0 ,e1 ,e2 ; 166ck (cudaEventCreate (& e0 ));ck (cudaEventCreate (& e1 ));ck (cudaEventCreate (& e2 )); 167constexpr int N = 5 ; 168ck (cudaEventRecord (e0 )); 169for (int r = 0 ;r < N ;++ r ) k::qsa_block_scores_tc (dp ,dd ,dq ,dt ,nq ,max_blocks ,s ,ref ,nullptr ,active ); 170ck (cudaEventRecord (e1 )); 171for (int r = 0 ;r < N ;++ r ) 172 k::qsa_block_scores_two_pass (dp ,dd ,dq ,dt ,nq ,nq_cap ,max_blocks ,s ,two ,scratch ,sbytes ,nullptr ,active ); 173ck (cudaEventRecord (e2 )); 174ck (cudaEventSynchronize (e2 )); 175float t3 = 0 ,t2 = 0 ; 176ck (cudaEventElapsedTime (& t3 ,e0 ,e1 ));ck (cudaEventElapsedTime (& t2 ,e1 ,e2 )); 177 std::printf (" time per call (synthetic, one run): 3xTF32 scorer %.3f ms, two-pass %.3f ms (keys once per chunk " 178"not included)\n" ,t3 /N ,t2 /N ); 179 k::qsa_two_pass_stats (st , true,nullptr ); 180cudaEventDestroy (e0 );cudaEventDestroy (e1 );cudaEventDestroy (e2 ); 181 } 182ck (cudaFree (dp ));ck (cudaFree (dd ));ck (cudaFree (dq ));ck (cudaFree (dt ));ck (cudaFree (ref ));ck (cudaFree (two )); 183ck (cudaFree (ref_ids ));ck (cudaFree (two_ids ));ck (cudaFree (scratch )); 184return ok ; 185} 186}// namespace 187 188int main () { 189#if defined(STRATA_USE_HIP )|| defined(STRATA_HIP_GFX906 ) 190// AMD: the two-pass scorer is CUDA-only (qsa_select.cu builds stubs under HIP), so the engine keeps today's scorer 191 std::puts ("SKIP: the two-pass scorer is CUDA-only" ); 192return 77 ; 193#endif 194#if defined(_WIN32 ) 195if (std::getenv ("STRATA_SELECT_TWO_PASS" )== nullptr )_putenv_s ("STRATA_SELECT_TWO_PASS" ,"1" ); 196#else 197setenv ("STRATA_SELECT_TWO_PASS" ,"1" ,0 );// read once, at the first call 198#endif 199int devices = 0 ; 200if (cudaGetDeviceCount (& devices )!= cudaSuccess || devices == 0 ) { 201 std::puts ("SKIP: no CUDA device" ); 202return 77 ; 203 } 204if (!k::qsa_two_pass_on ()) { 205 std::puts ("FAIL: STRATA_SELECT_TWO_PASS is set to something other than 1" ); 206return 1 ; 207 } 208const Case cases []= { 209 {2100 ,64 ,kNormal , false}, {4096 ,256 ,kNormal , false}, {9000 ,37 ,kNormal , false}, 210 {20000 ,256 ,kNormal , false}, {20481 ,256 ,kSmall , false}, {32768 ,256 ,kIndexer , false}, 211 {40000 ,256 ,kWide , false}, {50000 ,200 ,kNear , false}, {70000 ,256 ,kDup , false}, 212 {131072 ,256 ,kIndexer , false}, {131075 ,129 ,kNormal , false}, {262144 ,256 ,kIndexer , true}, 213 {262144 ,256 ,kNormal , true}, {200003 ,256 ,kSmall , false}, {65536 ,256 ,kIndexer , true}, 214 }; 215bool all = true; 216for (const int64_t stride : {(int64_t )0 , (int64_t )65538 }) 217for (const Case & c :cases )all = run (c ,stride )&& all ; 218if (!all ) { 219 std::puts ("FAIL: the two-pass selection differs from the 3xTF32 scorer's" ); 220return 1 ; 221 } 222 std::puts ("PASS: two-pass ids identical to the 3xTF32 scorer's, scored-again blocks bitwise, kept blocks inside the bound" ); 223return 0 ; 224}