okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
7f46672a4
main
1// metal/tests/qsa_parity.cpp - QSA decode (qsa.metal) stage by stage against a CPU reference, and its speed. 2// 3// qsa_parity [P] a context of P cells built by qsa_prep (default 3000: the selection is active above 4// 2051), then a window of 3 tokens: prep, score, top-k, attention, merge. Each stage is 5// checked against the CPU fed with the GPU's inputs to that stage; the ids exactly. 6// qsa_parity --bench [P] GPU time of the window's kernels at context P, 1 and 3 tokens 7#include "mtl_rt.h" 8#include "ref_quant.h" 9#include "engine/geo.h" 10 11#include <algorithm> 12#include <cmath> 13#include <cstdio> 14#include <cstdlib> 15#include <cstring> 16#include <string> 17#include <vector> 18 19namespace { 20constexpr int QH = strata_metal::geo::QH ,QKV = strata_metal::geo::QKV ,QD = strata_metal::geo::QD ,IH = strata_metal::geo::IH ,ID = strata_metal::geo::ID , 21BUDGET = strata_metal::geo::BUD ,CH = 64 ,NCH = (BUDGET + CH - 1 ) /CH ; 22struct QsaArgs {uint32_t pos0 ,pos_base ,max_cells ,n_tok ;float eps ; }; 23double median (std::vector < double > v ) { std::sort (v .begin (),v .end ());return v [v .size () /2 ]; } 24struct Err { 25double se = 0 ,sr = 0 ; 26void add (double g ,double r ) {se += (g - r )* (g - r );sr += r * r ; } 27double l2 ()const {return sr > 0 ? std::sqrt (se /sr ) : std::sqrt (se ); } 28}; 29float h2f (uint16_t h ) {return ref::f16_to_f32 (h ); } 30}// namespace 31 32int main (int argc ,char ** argv ) { 33bool bench = false; 34int P = 3000 ; 35for (int i = 1 ;i < argc ;++ i ) { 36 std::string a = argv [i ]; 37if (a == "--bench" )bench = true; 38else P = std::atoi (argv [i ]); 39 } 40const int MAXT = 8 ,MAXC = std::max (4096 , (P + 64 ) /4 * 4 + 64 ); 41 mtl::Context cx ; 42const int lib = cx .compile ({"qsa.metal" ,"qsa2.metal" }, strata_metal::geo::prelude ()+ "#define NO_GGML_COMMON 1\n" ); 43// QSA_TOPK=1: the v1 top-k; QSA_ATTN=1|2|3 (default 3): which attention (2 has its own chunking and merge) 44const int av = std::getenv ("QSA_ATTN" ) ? std::atoi (std::getenv ("QSA_ATTN" )) :1 ; 45const bool v2 = av == 2 ; 46 mtl::Pipeline pprep = cx .pipeline (lib ,"qsa_prep" , mtl::Constants ().b (24 , std::getenv ("QSA_MROPE" )!= nullptr )),pscore = cx .pipeline (lib ,"qsa_score" ), 47ptopk = cx .pipeline (lib , std::getenv ("QSA_TOPK" ) ?"qsa_topk" :"qsa_topk2" ), 48pattn = cx .pipeline (lib ,av == 1 ?"qsa_attn" :av == 2 ?"qsa_attn2" :"qsa_attn3" ), 49pmerge = cx .pipeline (lib ,v2 ?"qsa_merge2" :"qsa_merge" ); 50const int MB = MAXC /4 + 2 ; 51// per-cell inputs for every cell (context + window) 52const int NC = P + MAXT ; 53 mtl::Buffer qfull = cx .alloc (4 * (size_t )NC * QH * 2 * QD ),kc = cx .alloc (4 * (size_t )NC * QKV * QD ), 54vc = cx .alloc (4 * (size_t )NC * QKV * QD ),iq = cx .alloc (4 * (size_t )NC * IH * ID ), 55ik = cx .alloc (4 * (size_t )NC * ID ),qn = cx .alloc (4 * QD ),kn = cx .alloc (4 * QD ),iqn = cx .alloc (4 * ID ), 56ikn = cx .alloc (4 * ID ),cs = cx .alloc (8 * (size_t )(MAXC + 16 )* 32 ),qcur = cx .alloc (4 * MAXT * QH * QD ), 57qidx = cx .alloc (4 * MAXT * IH * ID ),kq = cx .alloc ((size_t )MAXC * QKV * QD ),vq = cx .alloc ((size_t )MAXC * QKV * QD ), 58ksc = cx .alloc (2 * (size_t )MAXC * QKV * 4 ),vsc = cx .alloc (2 * (size_t )MAXC * QKV * 4 ),tail = cx .alloc (4 * 4 * ID ), 59dead = cx .alloc (4 * ID ),pooled = cx .alloc (4 * (size_t )MB * ID ),scores = cx .alloc (4 * (size_t )MAXT * MB ), 60ids = cx .alloc (4 * MAXT * BUDGET ),part = cx .alloc (4 * (size_t )MAXT * 2 * NCH * QH * (QD + 2 )), 61xp = cx .alloc (4 * (4 * MAXT * QH * QD + MAXT * QH * QD /16 )); 62 ref::Rng r (23 ); 63for (size_t i = 0 ;i < qfull .bytes /4 ;++ i )qfull .as < float > ()[i ]= r .sym ()* 2.0f ; 64for (size_t i = 0 ;i < kc .bytes /4 ;++ i )kc .as < float > ()[i ]= r .sym ()* 2.0f ; 65for (size_t i = 0 ;i < vc .bytes /4 ;++ i )vc .as < float > ()[i ]= r .sym (); 66for (size_t i = 0 ;i < iq .bytes /4 ;++ i )iq .as < float > ()[i ]= r .sym (); 67for (size_t i = 0 ;i < ik .bytes /4 ;++ i )ik .as < float > ()[i ]= r .sym (); 68for (int i = 0 ;i < QD ;++ i ) {qn .as < float > ()[i ]= 1.0f + 0.2f * r .sym ();kn .as < float > ()[i ]= 1.0f + 0.2f * r .sym (); } 69for (int i = 0 ;i < ID ;++ i ) {iqn .as < float > ()[i ]= 1.0f + 0.2f * r .sym ();ikn .as < float > ()[i ]= 1.0f + 0.2f * r .sym (); } 70const uint32_t pos_base = 0 ; 71// QSA_MROPE=1: qsa_prep with the M-RoPE table (function constant 24): random (t, h, w) positions per cell, the CPU 72// reference rotating pair i by row tab[cell * 3 + i % 3]; QSA_MROPE=id: the identity table, checked bitwise 73// against the plain kernel 74const char * mre = std::getenv ("QSA_MROPE" ); 75const bool mrope = mre != nullptr ,mid = mrope && std::string (mre )== "id" ; 76 mtl::Buffer mtab = cx .alloc (4 * 3 * (size_t )(MAXC + 16 )); 77 { 78 ref::Rng rm (77 ); 79for (int c = 0 ;c < MAXC + 16 ;++ c ) 80for (int k = 0 ;k < 3 ;++ k )mtab .as < int > ()[c * 3 + k ]= mid ?c : (int )(rm .next () % (uint64_t )(MAXC + 16 )); 81 } 82for (int p = 0 ;p < MAXC + 16 ;++ p ) 83for (int i = 0 ;i < 32 ;++ i ) { 84const double inv = std::pow (1e7 ,-2.0 * i /64.0 ),th = (double )p * inv ; 85cs .as < float > ()[(p * 32 + i )* 2 ]= (float )std::cos (th ); 86cs .as < float > ()[(p * 32 + i )* 2 + 1 ]= (float )std::sin (th ); 87 } 88auto prep = [& ](uint32_t pos0 ,int nt ) { 89QsaArgs a {pos0 ,pos_base , (uint32_t )MAXC , (uint32_t )nt ,1e-6f }; 90 mtl::Dispatch d ; 91d .p = & pprep ; 92d .args = {mtl::Arg ::B (qfull ,4 * (size_t )pos0 * QH * 2 * QD ), mtl::Arg ::B (kc ,4 * (size_t )pos0 * QKV * QD ), 93 mtl::Arg ::B (vc ,4 * (size_t )pos0 * QKV * QD ), mtl::Arg ::B (iq ,4 * (size_t )pos0 * IH * ID ), 94 mtl::Arg ::B (ik ,4 * (size_t )pos0 * ID ), mtl::Arg ::B (qn ), mtl::Arg ::B (kn ), mtl::Arg ::B (iqn ), 95 mtl::Arg ::B (ikn ), mtl::Arg ::B (cs ), mtl::Arg ::B (qcur ), mtl::Arg ::B (qidx ), mtl::Arg ::B (kq ), 96 mtl::Arg ::B (vq ), mtl::Arg ::B (ksc ), mtl::Arg ::B (vsc ), mtl::Arg ::B (tail ), mtl::Arg ::B (dead ), 97 mtl::Arg ::B (pooled ), mtl::Arg ::V (a ), mtl::Arg ::B (mtab )}; 98d .grid [0 ]= strata_metal::geo::QPREP ; 99d .grid [1 ]= nt ; 100d .tg [0 ]= 256 ; 101return d ; 102 }; 103auto window = [& ](uint32_t pos0 ,int nt , std::vector < mtl::Dispatch >& ds ) { 104QsaArgs a {pos0 ,pos_base , (uint32_t )MAXC , (uint32_t )nt ,1e-6f }; 105ds .push_back (prep (pos0 ,nt )); 106 mtl::Dispatch s ; 107s .p = & pscore ; 108s .args = {mtl::Arg ::B (qidx ), mtl::Arg ::B (pooled ), mtl::Arg ::B (dead ), mtl::Arg ::B (scores ), mtl::Arg ::V (a )}; 109s .grid [0 ]= ((pos0 + nt ) /4 + 1 + 7 ) /8 ; 110s .grid [1 ]= nt ; 111s .tg [0 ]= 256 ; 112ds .push_back (s ); 113 mtl::Dispatch k ; 114k .p = & ptopk ; 115k .args = {mtl::Arg ::B (scores ), mtl::Arg ::B (ids ), mtl::Arg ::V (a )}; 116k .grid [0 ]= nt ; 117k .tg [0 ]= 1024 ; 118ds .push_back (k ); 119 mtl::Dispatch at ; 120at .p = & pattn ; 121at .args = {mtl::Arg ::B (qcur ), mtl::Arg ::B (kq ), mtl::Arg ::B (vq ), mtl::Arg ::B (ksc ), mtl::Arg ::B (vsc ), 122 mtl::Arg ::B (ids ), mtl::Arg ::B (part ), mtl::Arg ::V (a )}; 123at .grid [0 ]= v2 ? (BUDGET + 31 ) /32 :NCH ; 124at .grid [1 ]= v2 ?QKV * 2 :QKV ; 125at .grid [2 ]= nt ; 126at .tg [0 ]= 256 ; 127ds .push_back (at ); 128 mtl::Dispatch m ; 129m .p = & pmerge ; 130m .args = {mtl::Arg ::B (part ), mtl::Arg ::B (qfull ,4 * (size_t )pos0 * QH * 2 * QD ), mtl::Arg ::B (xp ), mtl::Arg ::V (a )}; 131m .grid [0 ]= QH ; 132m .grid [1 ]= nt ; 133m .tg [0 ]= 256 ; 134ds .push_back (m ); 135 }; 136// the context, one cell at a time 137 { 138 std::vector < mtl::Dispatch > ds ; 139for (int p = 0 ;p < P ;++ p )ds .push_back (prep (p ,1 )); 140cx .run (ds ); 141 } 142if (bench ) { 143 std::printf ("device %s, context %d cells\n" ,cx .device_name ().c_str (),P ); 144for (int nt : {1 ,3 }) { 145 std::vector < mtl::Dispatch > ds ; 146window (P ,nt ,ds ); 147const char * names []= {"prep" ,"score" ,"topk" ,"attn" ,"merge" }; 148double total = 0 ; 149for (int i = 0 ;i < 5 ;++ i ) { 150 std::vector < mtl::Dispatch > one (32 ,ds [i ]); 151cx .warm (one ,0.05 ); 152 std::vector < double > t ; 153for (int k = 0 ;k < 7 ;++ k )t .push_back (cx .run (one ) /32 ); 154 std::printf (" ntok %d %-6s %7.2f us\n" ,nt ,names [i ],median (t )* 1e6 ); 155total += median (t ); 156 } 157 std::vector < double > t ; 158for (int k = 0 ;k < 7 ;++ k )t .push_back (cx .run (ds )); 159 std::printf (" ntok %d window (5 dependent dispatches): %.2f us (sum of parts %.2f)\n" ,nt ,median (t )* 1e6 , 160total * 1e6 ); 161 } 162return 0 ; 163 } 164const int NT = 3 ; 165 std::vector < mtl::Dispatch > ds ; 166window (P ,NT ,ds ); 167// stage by stage, re-reading GPU state in between 168cx .run ({ds [0 ]}); 169int fails = 0 ; 170// ---- prep: qcur, qidx, the window cells' KV codes and the pooled keys vs CPU 171 { 172Err eq ,ei ,ekv ,ep ; 173auto normrope = [& ](const float * x ,const float * g ,int w ,int absp ,bool rope , std::vector < double >& out ) { 174double ss = 0 ; 175for (int i = 0 ;i < w ;++ i )ss += (double )x [i ]* x [i ]; 176const double rs = 1.0 / std::sqrt (ss /w + 1e-6 ); 177out .assign (w ,0.0 ); 178for (int i = 0 ;i < w ;++ i )out [i ]= rs * x [i ]* g [i ]; 179if (rope ) 180for (int i = 0 ;i < 32 ;++ i ) { 181const int pp = mrope ?mtab .as < int > ()[absp * 3 + i %3 ] :absp ; 182const double c = cs .as < float > ()[(pp * 32 + i )* 2 ],s = cs .as < float > ()[(pp * 32 + i )* 2 + 1 ]; 183const double a = out [i ],b = out [i + 32 ]; 184out [i ]= a * c - b * s ; 185out [i + 32 ]= a * s + b * c ; 186 } 187 }; 188 std::vector < double > o ; 189for (int t = 0 ;t < NT ;++ t ) { 190const int cell = P + t ; 191for (int h = 0 ;h < QH ;++ h ) { 192normrope (qfull .as < float > ()+ ((size_t )cell * QH + h )* 2 * QD ,qn .as < float > (),QD ,cell , true,o ); 193for (int i = 0 ;i < QD ;++ i )eq .add (qcur .as < float > ()[(t * QH + h )* QD + i ],o [i ]); 194 } 195for (int h = 0 ;h < IH ;++ h ) { 196normrope (iq .as < float > ()+ ((size_t )cell * IH + h )* ID ,iqn .as < float > (),ID ,cell , true,o ); 197for (int i = 0 ;i < ID ;++ i )ei .add (qidx .as < float > ()[(t * IH + h )* ID + i ],o [i ]); 198 } 199for (int h = 0 ;h < QKV ;++ h ) { 200normrope (kc .as < float > ()+ ((size_t )cell * QKV + h )* QD ,kn .as < float > (),QD ,cell , true,o ); 201for (int i = 0 ;i < QD ;++ i ) { 202const size_t row = (size_t )cell * QKV + h ; 203const double deq = (double )(int8_t )kq .as < int8_t > ()[row * QD + i ]* h2f (ksc .as < uint16_t > ()[row * 4 + i /64 ]); 204ekv .add (deq ,o [i ]); 205 } 206 } 207 } 208// pooled keys of the last few completed blocks 209const int nb = (P + NT ) /4 ; 210for (int b = std::max (0 ,nb - 8 );b < nb ;++ b ) { 211 std::vector < float > m (ID ); 212for (int i = 0 ;i < ID ;++ i ) 213m [i ]= (((ik .as < float > ()[(4 * b )* ID + i ]+ ik .as < float > ()[(4 * b + 1 )* ID + i ])+ 214ik .as < float > ()[(4 * b + 2 )* ID + i ])+ ik .as < float > ()[(4 * b + 3 )* ID + i ])* 0.25f ; 215normrope (m .data (),ikn .as < float > (),ID ,4 * b , true,o ); 216for (int i = 0 ;i < ID ;++ i )ep .add (pooled .as < float > ()[b * ID + i ],o [i ]); 217 } 218// int8 quantization error is ~1/254 of max|x| per group: the KV check is a quantization tolerance 219const bool ok = eq .l2 ()< 1e-5 && ei .l2 ()< 1e-5 && ep .l2 ()< 1e-5 && ekv .l2 ()< 6e-3 ; 220fails += !ok ; 221 std::printf ("prep: q rel L2 %.2e, indexer q %.2e, pooled keys %.2e, K int8 (vs float) %.2e %s\n" ,eq .l2 (), 222ei .l2 (),ep .l2 (),ekv .l2 (),ok ?"PASS" :"FAIL" ); 223 } 224// ---- score 225cx .run ({ds [1 ]}); 226 { 227Err es ; 228for (int t = 0 ;t < NT ;++ t ) { 229const int n_kv = P + t + 1 ,n_bid = n_kv /4 ; 230for (int b = 0 ;b <=n_bid ;++ b ) { 231const float * key = b == n_bid ?dead .as < float > () :pooled .as < float > ()+ b * ID ; 232double s = 0 ; 233for (int h = 0 ;h < IH ;++ h ) { 234double d = 0 ; 235for (int i = 0 ;i < ID ;++ i )d += (double )qidx .as < float > ()[(t * IH + h )* ID + i ]* key [i ]; 236s += std::max (d ,0.0 ); 237 } 238if (b == n_bid && (n_kv & 3 )) { 239// float(s + 1e9) keeps no bits of s: only check that the bias is there 240if (!(scores .as < float > ()[t * MB + b ] >=1e9f ))es .add (1.0 ,0.0 ); 241 }else { 242es .add (scores .as < float > ()[t * MB + b ],s ); 243 } 244 } 245 } 246const bool ok = es .l2 ()< 1e-5 ; 247fails += !ok ; 248 std::printf ("score: rel L2 %.2e (tail +1e9 checked separately) %s\n" ,es .l2 (),ok ?"PASS" :"FAIL" ); 249 } 250// ---- top-k (exact, from the GPU's scores) 251cx .run ({ds [2 ]}); 252 { 253int bad = 0 ; 254for (int t = 0 ;t < NT ;++ t ) { 255const int n_kv = P + t + 1 ,n_bid = n_kv /4 ,width = std::min (n_kv ,BUDGET ); 256 std::vector < int > cells (n_kv ); 257for (int c = 0 ;c < n_kv ;++ c )cells [c ]= c ; 258if (n_kv > BUDGET ) { 259const float * sc = scores .as < float > ()+ t * MB ; 260 std::stable_sort (cells .begin (),cells .end (), [& ](int x ,int y ) {return sc [x /4 ]> sc [y /4 ]; }); 261cells .resize (width ); 262 std::sort (cells .begin (),cells .end ()); 263 } 264 (void )n_bid ; 265for (int i = 0 ;i < width ;++ i )bad += ids .as < int > ()[t * BUDGET + i ]!= cells [i ]; 266 } 267fails += bad != 0 ; 268 std::printf ("top-k: %d of %d ids differ (context %d: selection %s) %s\n" ,bad ,NT * std::min (P + 1 ,BUDGET ),P , 269P + 1 > BUDGET ?"active" :"identity" ,bad ?"FAIL" :"PASS" ); 270 } 271// ---- attention + merge (from the GPU's qcur, ids and KV codes) 272cx .run ({ds [3 ],ds [4 ]}); 273 { 274Err eo ; 275for (int t = 0 ;t < NT ;++ t ) { 276const int n_kv = P + t + 1 ,width = std::min (n_kv ,BUDGET ); 277for (int h = 0 ;h < QH ;++ h ) { 278const int g = h / (QH /QKV ); 279 std::vector < double > s (width ); 280double mx = -1e300 ; 281for (int c = 0 ;c < width ;++ c ) { 282const size_t row = (size_t )ids .as < int > ()[t * BUDGET + c ]* QKV + g ; 283double d = 0 ; 284for (int i = 0 ;i < QD ;++ i ) 285d += (double )qcur .as < float > ()[(t * QH + h )* QD + i ]* (int8_t )kq .as < int8_t > ()[row * QD + i ]* 286h2f (ksc .as < uint16_t > ()[row * 4 + i /64 ]); 287s [c ]= d /16.0 ; 288mx = std::max (mx ,s [c ]); 289 } 290double l = 0 ; 291for (int c = 0 ;c < width ;++ c )l += (s [c ]= std::exp (s [c ]- mx )); 292for (int i = 0 ;i < QD ;++ i ) { 293double o = 0 ; 294for (int c = 0 ;c < width ;++ c ) { 295const size_t row = (size_t )ids .as < int > ()[t * BUDGET + c ]* QKV + g ; 296o += s [c ]* (int8_t )vq .as < int8_t > ()[row * QD + i ]* h2f (vsc .as < uint16_t > ()[row * 4 + i /64 ]); 297 } 298o /=l ; 299const double gate = qfull .as < float > ()[((size_t )(P + t )* QH + h )* 2 * QD + QD + i ]; 300eo .add (xp .as < float > ()[t * QH * QD + h * QD + i ],o / (1.0 + std::exp (- gate ))); 301 } 302 } 303 } 304const bool ok = eo .l2 ()< 1e-5 ; 305fails += !ok ; 306 std::printf ("attention + gate: rel L2 %.2e %s\n" ,eo .l2 (),ok ?"PASS" :"FAIL" ); 307 } 308 std::printf ("%s\n" ,fails ?"SOME FAILED" :"ALL PASS" ); 309return fails ?1 :0 ; 310}