okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
c954f5bd1
main
1// src/core/spec_prob_test.cpp - probabilistic draft acceptance (include/strata/core/spec_prob.hpp), no GPU. 2// 3// A reference rejection sampler on synthetic target distributions p and drafter distributions q over a 16-token 4// vocabulary; 2,000,000 trials per case. Each trial draws a draft d from q, judges it with spec_verify_row and 5// records the token the row emits; a chi-square test (99.9% bound) compares the emitted histogram with p. If 6// min(1, p/q) plus the residual preserved p only approximately the test would fail; two controls with a deliberately 7// wrong rule must fail it, which shows the test can tell. 8// 9// The cases: q = p; q = a point mass (the argmax draft, no list); q disjoint from p; q's support wider than p's; the 10// draft head's argmax outside p's support (p(d) = 0); a perturbed q. The chains: top_k 1, 5, 64; top_p 0.5, 0.95; 11// min_p 0.1; temperature 0.3, 1.0, 1.5 - p and q each cut by their OWN chain (q never borrows p's cut), the sampler's 12// own arithmetic (top_p's cut in double over the top_k list, min_p in logit space, temperature after). 13// Then a two-token WINDOW over a tiny Markov model checks the JOINT of the first two tokens (a wrong residual shows 14// up in the pairs first), with a draft of depth 2 whose second row is conditioned on the first draft. 15// Truncation regressions: a point-mass row inside a window that also has q rows (a lookup chain's tail) behaves as 16// exact match (accept probability p(d)), and "no list" is never "q = 0". 17#include "strata/core/spec_prob.hpp" 18 19#include <algorithm> 20#include <cmath> 21#include <cstdio> 22#include <random> 23#include <vector> 24 25using namespace strata::core ; 26 27namespace { 28 29constexpr int V = 16 ; 30int g_fail = 0 ; 31int g_cases = 0 ; 32 33struct Chain { 34int top_k ; 35float top_p ; 36float min_p ; 37float temp ; 38}; 39 40struct List { 41 std::vector < int32_t > id ; 42 std::vector < double > p ; 43 std::vector < float > q ;// the same probabilities as float, a drafter's list 44}; 45 46// the sampler's chain over logits (no penalties): top_k list in selection order, top_p cut in double on the raw 47// logits, min_p in logit space, temperature, normalise (sampled_probs_warp) 48List chain_list (const std::vector < float >& logit ,const Chain & c ) { 49 std::vector < int > ord (V ); 50for (int i = 0 ;i < V ;++ i )ord [i ]= i ; 51 std::stable_sort (ord .begin (),ord .end (), [& ](int a ,int b ) {return logit [a ]> logit [b ]; }); 52const int k = std::min (V , (c .top_k > 0 && c .top_k < 64 ) ?c .top_k :64 ); 53int n_keep = k ; 54const float mx = logit [ord [0 ]]; 55if (c .top_p < 1.0f ) { 56double sum = 0.0 ; 57 std::vector < double > e (k ); 58for (int i = 0 ;i < k ;++ i ) {e [i ]= std::exp ((double )logit [ord [i ]]- (double )mx );sum += e [i ]; } 59double cum = 0.0 ; 60int cut = k ; 61for (int i = 0 ;i < k ;++ i ) { 62cum += e [i ] /sum ; 63if (cum >= (double )c .top_p ) {cut = i + 1 ;break ; } 64 } 65n_keep = std::max (cut ,1 ); 66 } 67if (c .min_p > 0.0f ) { 68const float thresh = logit [ord [0 ]]+ std::log (c .min_p ); 69for (int i = 0 ;i < n_keep ;++ i ) 70if (logit [ord [i ]]< thresh ) {n_keep = i ;break ; } 71 } 72const float inv_t = 1.0f /c .temp ; 73float smx = logit [ord [0 ]]* inv_t ; 74for (int i = 1 ;i < n_keep ;++ i )smx = std::max (smx ,logit [ord [i ]]* inv_t ); 75List L ; 76double sum = 0.0 ; 77for (int i = 0 ;i < n_keep ;++ i ) { 78L .id .push_back (ord [i ]); 79L .p .push_back (std::exp ((double ) (logit [ord [i ]]* inv_t )- (double )smx )); 80sum += L .p .back (); 81 } 82for (double & x :L .p )x /=sum ; 83for (double x :L .p )L .q .push_back ((float )x ); 84return L ; 85} 86 87float uni (std::mt19937_64 & g ) {return (float ) (g () >>40 )* (1.0f /16777216.0f ); } 88 89int32_t draw (const List & L ,float u ) {// the sampler's inverse-CDF pick 90double cum = 0.0 ; 91int32_t pick = L .id .back (); 92for (size_t i = 0 ;i < L .id .size ();++ i ) { 93cum += L .p [i ]; 94if ((double )u < cum ) {pick = L .id [i ];break ; } 95 } 96return pick ; 97} 98 99// chi-square statistic of `count` against probabilities `prob` (cells with expectation < 5 are pooled), and the 99.9% 100// critical value for its degrees of freedom (Wilson-Hilferty) 101struct Chi {double stat ;int df ;double crit ; }; 102Chi chi_square (const std::vector < double >& count ,const std::vector < double >& prob ,double n ) { 103double stat = 0.0 ,pool_o = 0.0 ,pool_e = 0.0 ; 104int cells = 0 ; 105for (size_t i = 0 ;i < count .size ();++ i ) { 106const double e = prob [i ]* n ; 107if (e < 5.0 ) {pool_o += count [i ];pool_e += e ;continue ; } 108stat += (count [i ]- e )* (count [i ]- e ) /e ; 109++ cells ; 110 } 111if (pool_e >=5.0 ) {stat += (pool_o - pool_e )* (pool_o - pool_e ) /pool_e ;++ cells ; } 112else if (pool_o > pool_e + 6.0 * std::sqrt (pool_e )+ 10.0 )stat += 1e9 ;// far more hits than the thin tail's expectation 113const int df = std::max (1 ,cells - 1 ); 114const double z = 3.0902 ;// 99.9% 115const double a = 2.0 / (9.0 * df ); 116const double crit = df * std::pow (1.0 - a + z * std::sqrt (a ),3.0 ); 117return {stat ,df ,crit }; 118} 119 120void report (const char * name ,const Chi & c ,bool expect_fail = false) { 121++ g_cases ; 122const bool pass = c .stat <=c .crit ; 123const bool ok = expect_fail ? !pass :pass ; 124if (!ok )++ g_fail ; 125 std::printf (" %-4s %-58s chi2 %9.1f df %2d bound %6.1f%s\n" ,ok ?"ok" :"FAIL" ,name ,c .stat ,c .df ,c .crit , 126expect_fail ?" (control: must fail)" :"" ); 127} 128 129enum class Rule {Standard ,AlwaysAccept ,NoListMeansZeroQ }; 130 131// one row: draw d from q, judge it 132int32_t one_trial (std::mt19937_64 & g ,const List & P ,const List * Q ,int32_t point_d ,Rule rule ,bool * accepted ) { 133const SpecP sp {P .id .data (),P .p .data (), (int )P .id .size ()}; 134int32_t d ; 135SpecQ sq {nullptr ,nullptr ,-1 }; 136if (Q != nullptr ) { 137d = draw (* Q ,uni (g )); 138sq = SpecQ {Q -> id .data (),Q -> q .data (), (int )Q -> id .size ()}; 139 }else { 140d = point_d ; 141 } 142const float ua = uni (g ),ur = uni (g ); 143SpecResult r = spec_verify_row (sp ,d ,sq ,ua ,ur ); 144if (rule == Rule ::AlwaysAccept )r = {d ,1 }; 145if (rule == Rule ::NoListMeansZeroQ && Q == nullptr )r = {d ,0 };// "no q: q = 0": reject; (the residual is then p) 146if (rule == Rule ::NoListMeansZeroQ && Q == nullptr )r .token = draw (P ,ur ); 147* accepted = r .accepted != 0 ; 148return r .token ; 149} 150 151struct Setup { 152const char * name ; 153List P ; 154List Q ; 155bool point ;// q is a point mass at its argmax: no list 156int32_t d_point ; 157}; 158 159void run_case (const Setup & S ,int trials , std::mt19937_64 & g ,Rule rule ,bool expect_fail ,double * acc_rate ) { 160 std::vector < double > cnt (V ,0.0 ),prob (V ,0.0 ); 161for (size_t i = 0 ;i < S .P .id .size ();++ i )prob [(size_t )S .P .id [i ]]= S .P .p [i ]; 162long long acc = 0 ; 163for (int t = 0 ;t < trials ;++ t ) { 164bool a = false; 165const int32_t tok = one_trial (g ,S .P ,S .point ?nullptr :& S .Q ,S .d_point ,rule ,& a ); 166cnt [(size_t )tok ]+= 1.0 ; 167acc += a ; 168 } 169// a token outside p's support must never be emitted 170double outside = 0.0 ; 171for (int i = 0 ;i < V ;++ i ) 172if (prob [(size_t )i ]== 0.0 )outside += cnt [(size_t )i ]; 173Chi c = chi_square (cnt ,prob , (double )trials ); 174if (outside > 0.0 )c .stat += 1e9 ; 175if (acc_rate )* acc_rate = (double )acc /trials ; 176char nm [160 ]; 177 std::snprintf (nm ,sizeof nm ,"%s (accept %.3f)" ,S .name , (double )acc /trials ); 178report (nm ,c ,expect_fail ); 179} 180 181std::vector < float > rand_logits (std::mt19937_64 & g ,float spread ) { 182 std::normal_distribution < float > nd (0.0f ,spread ); 183 std::vector < float > l (V ); 184for (float & x :l )x = nd (g ); 185return l ; 186} 187 188}// namespace 189 190int main () { 191 std::mt19937_64 g (20261006 ); 192const int N = 2000000 ; 193const std::vector < Chain > chains = {{64 ,1.0f ,0.0f ,1.0f }, {1 ,1.0f ,0.0f ,1.0f }, {5 ,1.0f ,0.0f ,1.0f }, 194 {64 ,0.5f ,0.0f ,1.0f }, {64 ,0.95f ,0.0f ,1.0f }, {20 ,0.95f ,0.05f ,0.7f }, 195 {64 ,1.0f ,0.1f ,1.0f }, {64 ,1.0f ,0.0f ,0.3f }, {64 ,1.0f ,0.0f ,1.5f }, 196 {8 ,0.9f ,0.02f ,1.0f }}; 197 std::printf ("spec_prob_test: %d trials per case, 16-token vocabulary\n" ,N ); 198for (const Chain & c :chains ) { 199 std::printf ("chain top_k %d top_p %.2f min_p %.2f temp %.1f\n" ,c .top_k ,c .top_p ,c .min_p ,c .temp ); 200const std::vector < float > lp = rand_logits (g ,2.0f ); 201const List P = chain_list (lp ,c ); 202// q = p 203run_case ({"q = p" ,P ,P , false,0 },N ,g ,Rule ::Standard , false,nullptr ); 204// a perturbed q (the typical drafter), cut by its own chain 205 std::vector < float > lq = lp ; 206 std::normal_distribution < float > nd (0.0f ,0.8f ); 207for (float & x :lq )x += nd (g ); 208run_case ({"perturbed q" ,P ,chain_list (lq ,c ), false,0 },N ,g ,Rule ::Standard , false,nullptr ); 209// q a point mass at its argmax (no list: the argmax draft) 210 { 211const List Qp = chain_list (lq ,Chain {1 ,1.0f ,0.0f ,1.0f }); 212run_case ({"q = point mass (argmax draft, no list)" ,P ,Qp , true,Qp .id [0 ]},N ,g ,Rule ::Standard , false, 213nullptr ); 214 } 215// q disjoint from p: the drafter's top tokens are the target's tail 216 { 217 std::vector < float > ld (V ); 218for (int i = 0 ;i < V ;++ i )ld [i ]= - lp [i ]; 219run_case ({"q disjoint from p (inverted logits)" ,P ,chain_list (ld ,c ), false,0 },N ,g ,Rule ::Standard , 220 false,nullptr ); 221 } 222// q's support wider than p's: p cut hard, q uncut 223run_case ({"q support wider than p's" ,P ,chain_list (lq ,Chain {64 ,1.0f ,0.0f ,1.0f }), false,0 },N ,g , 224Rule ::Standard , false,nullptr ); 225// the drafter's argmax is outside p's support: p(d) = 0 for the point-mass draft 226 { 227const List Qp = chain_list (lq ,Chain {1 ,1.0f ,0.0f ,1.0f }); 228 std::vector < float > lo = lp ; 229lo [(size_t )Qp .id [0 ]]= -50.0f ;// the target gives the drafter's favourite no mass 230const List Po = chain_list (lo ,c ); 231run_case ({"p(argmax draft) = 0, point mass" ,Po ,Qp , true,Qp .id [0 ]},N ,g ,Rule ::Standard , false,nullptr ); 232 } 233 } 234// controls: wrong rules must fail the test 235 { 236 std::printf ("controls\n" ); 237const Chain c {64 ,0.95f ,0.0f ,1.0f }; 238const std::vector < float > lp = rand_logits (g ,2.0f ); 239 std::vector < float > lq = lp ; 240 std::normal_distribution < float > nd (0.0f ,1.0f ); 241for (float & x :lq )x += nd (g ); 242const List P = chain_list (lp ,c ); 243run_case ({"always accept the draft" ,P ,chain_list (lq ,c ), false,0 },200000 ,g ,Rule ::AlwaysAccept , true, 244nullptr ); 245const List Qp = chain_list (lq ,Chain {1 ,1.0f ,0.0f ,1.0f }); 246const double pd = [& ] {double v = 0 ;for (size_t i = 0 ;i < P .id .size ();++ i )if (P .id [i ]== Qp .id [0 ])v = P .p [i ];return v ; }(); 247double acc_std = 0 ,acc_zero = 0 ; 248run_case ({"point mass, standard rule" ,P ,Qp , true,Qp .id [0 ]},200000 ,g ,Rule ::Standard , false,& acc_std ); 249run_case ({"point mass, 'no list = q 0' (rejects all: #29924)" ,P ,Qp , true,Qp .id [0 ]},200000 ,g , 250Rule ::NoListMeansZeroQ , false,& acc_zero ); 251++ g_cases ; 252const bool ok = std::fabs (acc_std - pd )< 0.01 && acc_zero == 0.0 ; 253if (!ok )++ g_fail ; 254 std::printf (" %-4s point-mass accept rate %.4f = p(d) %.4f; the q = 0 rule accepts %.4f\n" ,ok ?"ok" :"FAIL" , 255acc_std ,pd ,acc_zero ); 256 } 257 258// ---- the JOINT of the first two tokens over a Markov model, drafts of depth 2. 259// p0 over x0, p1(. | x0) over x1; the drafter q0, q1(. | d0) are perturbations; window = [d0, d1] verified by two 260// rows, then the continuation: after an accepted row the next row's pick; after a reject the row's own residual 261// token is x0 and the NEXT window starts from it (a plain sample of x1 from p1(. | x0)). 262for (const Chain & c : std::vector < Chain > {{64 ,1.0f ,0.0f ,1.0f }, {20 ,0.95f ,0.05f ,0.7f }, {5 ,0.5f ,0.0f ,1.5f }}) { 263 std::printf ("joint (x0, x1) over a Markov model: top_k %d top_p %.2f min_p %.2f temp %.1f\n" ,c .top_k ,c .top_p , 264c .min_p ,c .temp ); 265 std::vector < List > P1 (V ),Q1 (V ); 266const std::vector < float > l0 = rand_logits (g ,1.5f ); 267 std::vector < float > m0 = l0 ; 268 std::normal_distribution < float > nd (0.0f ,0.9f ); 269for (float & x :m0 )x += nd (g ); 270const List P0 = chain_list (l0 ,c ),Q0 = chain_list (m0 ,c ); 271for (int a = 0 ;a < V ;++ a ) { 272const std::vector < float > l1 = rand_logits (g ,1.5f ); 273 std::vector < float > m1 = l1 ; 274for (float & x :m1 )x += nd (g ); 275P1 [(size_t )a ]= chain_list (l1 ,c ); 276Q1 [(size_t )a ]= chain_list (m1 ,c ); 277 } 278 std::vector < double > cnt ((size_t )V * V ,0.0 ),prob ((size_t )V * V ,0.0 ); 279for (size_t i = 0 ;i < P0 .id .size ();++ i ) 280for (size_t j = 0 ;j < P1 [(size_t )P0 .id [i ]].id .size ();++ j ) 281prob [(size_t )P0 .id [i ]* V + (size_t )P1 [(size_t )P0 .id [i ]].id [j ]]= P0 .p [i ]* P1 [(size_t )P0 .id [i ]].p [j ]; 282long long acc_tokens = 0 ; 283for (int t = 0 ;t < N ;++ t ) { 284const int32_t d0 = draw (Q0 ,uni (g )); 285const int32_t d1 = draw (Q1 [(size_t )d0 ],uni (g )); 286// row 0 judges d0 against p0 287const SpecP s0 {P0 .id .data (),P0 .p .data (), (int )P0 .id .size ()}; 288const SpecQ q0 {Q0 .id .data (),Q0 .q .data (), (int )Q0 .id .size ()}; 289const float a0 = uni (g ),r0 = uni (g ); 290const SpecResult r = spec_verify_row (s0 ,d0 ,q0 ,a0 ,r0 ); 291const int32_t x0 = r .token ; 292int32_t x1 ; 293if (r .accepted ) { 294// row 1 (conditioned on the window's d0 == x0) judges d1 against p1(. | d0) 295const List & P = P1 [(size_t )x0 ]; 296const SpecP s1 {P .id .data (),P .p .data (), (int )P .id .size ()}; 297const List & Q = Q1 [(size_t )d0 ]; 298const SpecQ q1 {Q .id .data (),Q .q .data (), (int )Q .id .size ()}; 299const float a1 = uni (g ),r1 = uni (g ); 300x1 = spec_verify_row (s1 ,d1 ,q1 ,a1 ,r1 ).token ; 301++ acc_tokens ; 302 }else { 303x1 = draw (P1 [(size_t )x0 ],uni (g ));// the next window: row 0 of a fresh window, plain 304 } 305cnt [(size_t )x0 * V + (size_t )x1 ]+= 1.0 ; 306 } 307char nm [96 ]; 308 std::snprintf (nm ,sizeof nm ,"joint of 2 tokens (row-0 kept %.3f)" , (double )acc_tokens /N ); 309report (nm ,chi_square (cnt ,prob , (double )N )); 310 } 311 312// ---- truncation regressions 313 { 314 std::printf ("truncation regressions\n" ); 315// a window of 3 drafts: rows 0 and 1 carry q lists, row 2 is a lookup chain's point-mass tail. Row 2 must 316// accept with probability p(d) (exact match), whatever the lists are, and a shortened draft (n_q smaller than 317// the number of drafts: the tail now starts earlier) must not inherit an empty list as q = 0. 318const Chain c {20 ,0.95f ,0.0f ,0.7f }; 319const List P = chain_list (rand_logits (g ,2.0f ),c ); 320const SpecP sp {P .id .data (),P .p .data (), (int )P .id .size ()}; 321for (size_t pick : {0u ,1u ,3u }) { 322const int32_t d = P .id [std::min (pick ,P .id .size ()- 1 )]; 323long long acc = 0 ; 324const int n = 400000 ; 325for (int t = 0 ;t < n ;++ t )acc += spec_verify_row (sp ,d ,SpecQ {nullptr ,nullptr ,-1 },uni (g ),uni (g )).accepted ; 326double pd = 0 ; 327for (size_t i = 0 ;i < P .id .size ();++ i )if (P .id [i ]== d )pd = P .p [i ]; 328++ g_cases ; 329const double rate = (double )acc /n ,se = std::sqrt (pd * (1 - pd ) /n ); 330const bool ok = std::fabs (rate - pd )< 4.5 * se + 1e-9 ; 331if (!ok )++ g_fail ; 332 std::printf (" %-4s point-mass row: accept %.4f vs p(d) %.4f (4.5 se %.4f)\n" ,ok ?"ok" :"FAIL" ,rate ,pd , 3334.5 * se ); 334 } 335// a draft outside p's support (cut by top_p / top_k / min_p) is rejected and the replacement is in p's support 336const int32_t outside = [& ] { 337for (int v = 0 ;v < V ;++ v ) { 338bool in = false; 339for (int32_t id :P .id )in = in || id == v ; 340if (!in )return v ; 341 } 342return -1 ; 343 }(); 344long long bad = 0 ; 345for (int t = 0 ;t < 100000 && outside >=0 ;++ t ) { 346const SpecResult r = spec_verify_row (sp ,outside ,SpecQ {nullptr ,nullptr ,-1 },uni (g ),uni (g )); 347bad += r .accepted || r .token == outside ; 348 } 349++ g_cases ; 350if (bad != 0 || outside < 0 )++ g_fail ; 351 std::printf (" %-4s a draft outside top_k/top_p/min_p support is always rejected, replaced inside p (%lld bad)\n" , 352 (bad == 0 && outside >=0 ) ?"ok" :"FAIL" ,bad ); 353// p == q everywhere: always accepted (min(1, p/q) = 1), never a 0 / 0 354long long rej = 0 ; 355const List Q = P ; 356const SpecQ sq {Q .id .data (),Q .q .data (), (int )Q .id .size ()}; 357for (int t = 0 ;t < 200000 ;++ t ) { 358const int32_t d = draw (Q ,uni (g )); 359rej += !spec_verify_row (sp ,d ,sq ,uni (g ),uni (g )).accepted ; 360 } 361++ g_cases ; 362if (rej != 0 )++ g_fail ; 363 std::printf (" %-4s p == q: every draft is accepted (%lld rejected)\n" ,rej == 0 ?"ok" :"FAIL" ,rej ); 364 } 365 366 std::printf ("spec_prob_test: %d cases, %d failed\n" ,g_cases ,g_fail ); 367return g_fail == 0 ?0 :1 ; 368}