okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
54d7f7d7c
main
1// src/kernels/sampler_parity.cpp - P2.S2's test for the sampler chain. 2// 3// THE CHECK THAT MATTERS IS THAT THE ORDER IS OBSERVABLE. A sampler in the wrong order still returns a valid 4// token, so "it produced a token" proves nothing; and because temperature is MONOTONIC it does not change which 5// tokens `top_k` keeps, so a top-k-only fixture cannot see the order either. What it changes is `top_p`'s CUT: 6// at T < 1 the distribution sharpens, the cumulative mass reaches p sooner, and fewer tokens survive. 7// 8// So this builds a fixture where that happens, computes the greedy pick under BOTH orders, and requires them to 9// DIFFER - then requires the kernel to agree with the specified one. Without the first half, the test would 10// pass against either order. 11#include "strata/kernels/sampler.hpp" 12 13#include <cuda_runtime.h> 14 15#include <algorithm> 16#include <cmath> 17#include <cstdio> 18#include <cstdlib> 19#include <cstring> 20#include <limits> 21#include <random> 22#include <string> 23#include <vector> 24 25namespace { 26 27void check (cudaError_t e ,const char * what ) { 28if (e != cudaSuccess ) { 29 std::fprintf (stderr ,"%s: %s\n" ,what ,cudaGetErrorString (e )); 30 std::exit (1 ); 31 } 32} 33 34// The host reference for the specified order: top_k -> top_p -> temperature -> argmax. 35// `temp_first` swaps the first and last stages, which is the intuitive-but-wrong order. 36int reference_pick (const std::vector < float >& l ,const strata::kernels::SamplerParams & p ,bool temp_first ) { 37const int nv = (int )l .size (); 38const float inv_t = p .temperature > 0.0f ?1.0f /p .temperature :0.0f ; 39auto val = [& ](int v ) {return temp_first ?l [(size_t )v ]* inv_t :l [(size_t )v ]; }; 40 41 std::vector < int > ids ; 42const int k = p .top_k > 0 ?p .top_k :nv ; 43 std::vector < char > taken ((size_t )nv ,0 ); 44for (int i = 0 ;i < k ;++ i ) { 45int best = -1 ; 46float bv = 0 ; 47for (int v = 0 ;v < nv ;++ v ) { 48if (taken [(size_t )v ])continue ; 49if (best < 0 || val (v )> bv ) {best = v ;bv = val (v ); } 50 } 51taken [(size_t )best ]= 1 ; 52ids .push_back (best ); 53 } 54if (p .top_p < 1.0f ) { 55float mx = val (ids [0 ]); 56for (int v :ids )mx = std::fmax (mx ,val (v )); 57double sum = 0 ; 58for (int v :ids )sum += std::exp ((double )val (v )- (double )mx ); 59double cum = 0 ; 60int cut = (int )ids .size (); 61for (size_t i = 0 ;i < ids .size ();++ i ) { 62cum += std::exp ((double )val (ids [i ])- (double )mx ) /sum ; 63if (cum >= (double )p .top_p ) {cut = (int )i + 1 ;break ; } 64 } 65if (cut < p .min_keep )cut = p .min_keep < (int )ids .size () ?p .min_keep : (int )ids .size (); 66ids .resize ((size_t )cut ); 67 } 68return ids [0 ];// greedy: the largest SURVIVING logit, and `ids` is in descending order 69} 70 71// The number of survivors AFTER top_p, in the given order - the quantity the order actually changes. 72int reference_cut (const std::vector < float >& l ,const strata::kernels::SamplerParams & p ,bool temp_first ) { 73const int nv = (int )l .size (); 74const float inv_t = p .temperature > 0.0f ?1.0f /p .temperature :0.0f ; 75auto val = [& ](int v ) {return temp_first ?l [(size_t )v ]* inv_t :l [(size_t )v ]; }; 76const int k = p .top_k > 0 ?p .top_k :nv ; 77 std::vector < int > ids ; 78 std::vector < char > taken ((size_t )nv ,0 ); 79for (int i = 0 ;i < k ;++ i ) { 80int best = -1 ;float bv = 0 ; 81for (int v = 0 ;v < nv ;++ v ) { 82if (taken [(size_t )v ])continue ; 83if (best < 0 || val (v )> bv ) {best = v ;bv = val (v ); } 84 } 85taken [(size_t )best ]= 1 ;ids .push_back (best ); 86 } 87if (p .top_p < 1.0f ) { 88float mx = val (ids [0 ]); 89for (int v :ids )mx = std::fmax (mx ,val (v )); 90double sum = 0 ; 91for (int v :ids )sum += std::exp ((double )val (v )- (double )mx ); 92double cum = 0 ; 93int cut = (int )ids .size (); 94for (size_t i = 0 ;i < ids .size ();++ i ) { 95cum += std::exp ((double )val (ids [i ])- (double )mx ) /sum ; 96if (cum >= (double )p .top_p ) {cut = (int )i + 1 ;break ; } 97 } 98if (cut < p .min_keep )cut = p .min_keep < (int )ids .size () ?p .min_keep : (int )ids .size (); 99return cut ; 100 } 101return (int )ids .size (); 102} 103 104int run (const char * name ,const std::vector < float >& logits ,int n_tokens ,const strata::kernels::SamplerParams & p , 105const std::vector < int >& want ,const std::vector < int >& hist = {}, int hist_len = 0 ) { 106float * d_l = nullptr ; 107int * d_o = nullptr ; 108check ( cudaMalloc ( & d_l , logits . size () * sizeof (float)), "malloc logits" ); 109check ( cudaMalloc ( & d_o , (size_t) n_tokens * sizeof (int)), "malloc out" ); 110check ( cudaMemcpy ( d_l , logits . data (), logits . size () * sizeof (float), cudaMemcpyHostToDevice ), "copy" ); 111// -1 in every output slot first: a row the kernel leaves unwritten can never match (a verify window reads 112// every row, so "no output" is a wrong answer, not a skipped one) 113check ( cudaMemset ( d_o , 0xFF , (size_t) n_tokens * sizeof (int)), "fill out" ); 114int * d_h = nullptr ; 115if ( hist_len > 0 ) { 116check ( cudaMalloc ( & d_h , hist . size () * sizeof (int)), "malloc hist" ); 117check ( cudaMemcpy ( d_h , hist . data (), hist . size () * sizeof (int), cudaMemcpyHostToDevice ), "copy hist" ); 118} 119strata::kernels:: sample_tokens ( d_l , n_tokens , (int) ( logits . size () / n_tokens ), d_h , hist_len , p , d_o , 120nullptr ); 121std::vector < int > got ((size_t) n_tokens ); 122check ( cudaMemcpy ( got . data (), d_o , got . size () * sizeof (int), cudaMemcpyDeviceToHost ), "back" ); 123int bad = 0 ; 124for (int t = 0 ; t < n_tokens ; ++ t ) if ( got [(size_t) t ] != want [(size_t) t ]) ++ bad ; 125std:: printf ( " %-34s %s (%d of %d differ)" , name , bad ? "*** WRONG ***" : "matches" , bad , n_tokens ); 126if ( bad ) std:: printf ( " first: want %d got %d" , want [ 0 ], got [ 0 ]); 127std:: printf ( "\n" ); 128cudaFree ( d_l ); 129cudaFree ( d_o ); 130if ( d_h ) cudaFree ( d_h ); 131return bad ; 132} 133 134// The Philox draw, host side - a transcription of the kernel's `philox_uniform` so the SAMPLED pick (not 135// just the greedy argmax) can be pinned against a reference. `__umulhi(a, b)` is the high half of a 32x32 136// multiply, spelled `(uint32_t)(((uint64_t) a * b) >> 32)` here. 137struct PhiloxRound { 138uint32_t & c0 ; uint32_t & c1 ; uint32_t & c2 ; uint32_t & c3 ; 139void step (uint32_t k0 , uint32_t k1 ) const { 140const uint32_t hi0 = (uint32_t) (((uint64_t) 0x9E3779B9u * c0 ) >> 32 ); 141const uint32_t hi1 = (uint32_t) (((uint64_t) 0xBB67AE85u * c2 ) >> 32 ); 142const uint32_t lo0 = 0x9E3779B9u * c0 ; 143const uint32_t lo1 = 0xBB67AE85u * c2 ; 144const uint32_t n0 = hi1 ^ c1 ^ k0 ; 145const uint32_t n1 = lo1 ; 146const uint32_t n2 = hi0 ^ c3 ^ k1 ; 147const uint32_t n3 = lo0 ; 148c0 = n0 ; c1 = n1 ; c2 = n2 ; c3 = n3 ; 149} 150}; 151 152float host_philox_uniform (uint64_t seed , uint64_t counter ) { 153uint32_t c0 = (uint32_t) counter , c1 = (uint32_t) ( counter >> 32 ); 154uint32_t c2 = (uint32_t) seed , c3 = (uint32_t) ( seed >> 32 ); 155PhiloxRound r { c0 , c1 , c2 , c3 }; 156for (int i = 0 ; i < 10 ; ++ i ) r . step ((uint32_t) i , 0u ); 157return (float) ( c0 >> 8 ) * ( 1.0f / 16777216.0f ); 158} 159 160// The Gumbel-max noise, host side - a transcription of the kernel's `gumbel_exp` (STRATA_SPEC_GUMBEL): Exp(1) from 161// a splitmix64 hash of (seed, counter, token id). The pick is argmax_i p_i / E_i, an exact sample of p. 162double host_gumbel_exp (uint64_t seed , uint64_t counter , uint32_t token ) { 163uint64_t z = seed ^ ( counter * 0x9E3779B97F4A7C15ull ) ^ ((uint64_t) token * 0xD1B54A32D192ED03ull ); 164z += 0x9E3779B97F4A7C15ull ; 165z = ( z ^ ( z >> 30 )) * 0xBF58476D1CE4E5B9ull ; 166z = ( z ^ ( z >> 27 )) * 0x94D049BB133111EBull ; 167z ^= z >> 31 ; 168const double u = ((double) ( z >> 11 ) + 0.5 ) * ( 1.0 / 9007199254740992.0 ); 169return - std:: log ( u ); 170} 171 172// The full SAMPLED chain, host side - the kernel's `sampler_kernel` in serial form, in llama.cpp's order: 173// penalties on the raw logits during the top_k selection (ties to the lowest index), top_p's cut in double over 174// the top_k list, the min_p prefix cut on its survivors, the temperature, and one Philox draw at 175// (seed, counter + row). One penalties stage (issue #53: this reference used to repeat the kernel's second one). 176int sampled_reference ( const std::vector < float >& l , const std::vector < int >& hist , 177const strata::kernels::SamplerParams & p , int row ) { 178auto penal = [ & ](float logit , int count ) { 179if ( count <= 0 ) return logit ; 180if ( logit <= 0.0f ) logit *= p . penalty_repeat ; else logit /= p . penalty_repeat ; 181logit -= (float) count * p . penalty_freq + ( count > 0 ? 1.0f : 0.0f ) * p . penalty_present ; 182return logit ; 183}; 184auto count = [ & ](int v ) { int c = 0 ; for (int h : hist ) if ( h == v ) ++ c ; return c ; }; 185const int nv = (int) l . size (); 186const int KMAX = 64 ; // 1..64 as given; 0 (off) and wider keep the widest list, 64 187const int k = std:: min ( nv , ( p . top_k > 0 && p . top_k < KMAX ) ? p . top_k : KMAX ); 188std::vector < int > sel_ids ; 189std::vector < float > sel_logit ; 190std::vector < char > taken ((size_t) nv , 0 ); 191for (int i = 0 ; i < k ; ++ i ) { 192int best = -1 ; float bv = 0 ; 193for (int v = 0 ; v < nv ; ++ v ) { 194if ( taken [(size_t) v ]) continue ; 195const float s = penal ( l [(size_t) v ], count ( v )); 196if ( best < 0 || s > bv ) { best = v ; bv = s ; } 197} 198taken [(size_t) best ] = 1 ; 199sel_ids . push_back ( best ); sel_logit . push_back ( bv ); 200} 201// llama.cpp's order (issue #53): top_p over the whole top_k list, then min_p on its survivors 202const int n_sel = (int) sel_ids . size (); 203int n_keep = n_sel ; 204if ( p . top_p < 1.0f ) { 205double sum = 0.0 ; 206for (int i = 0 ; i < n_sel ; ++ i ) sum += std:: exp ((double) sel_logit [(size_t) i ] - (double) sel_logit [ 0 ]); 207double cum = 0.0 ; 208int cut = n_sel ; 209for (int i = 0 ; i < n_sel ; ++ i ) { 210cum += std:: exp ((double) sel_logit [(size_t) i ] - (double) sel_logit [ 0 ]) / sum ; 211if ( cum >= (double) p . top_p ) { cut = i + 1 ; break ; } 212} 213if ( cut < p . min_keep ) cut = p . min_keep < n_sel ? p . min_keep : n_sel ; 214n_keep = cut ; 215} 216if ( p . min_p > 0.0f ) { 217const float thresh = sel_logit [ 0 ] + std:: log ( p . min_p ); 218for (int i = 0 ; i < n_keep ; ++ i ) 219if ( sel_logit [(size_t) i ] < thresh ) { n_keep = i ; break ; } 220} 221const float inv_t = p . temperature > 0.0f ? 1.0f / p . temperature : 0.0f ; 222auto scaled = [ & ](int i ) { return sel_logit [(size_t) i ] * inv_t ; }; // one penalties stage, before (#53) 223float smx = scaled ( 0 ); 224for (int i = 1 ; i < n_keep ; ++ i ) smx = std:: fmax ( smx , scaled ( i )); 225double sum = 0.0 ; 226for (int i = 0 ; i < n_keep ; ++ i ) sum += std:: exp ((double) scaled ( i ) - (double) smx ); 227int pick = sel_ids [(size_t) ( n_keep - 1 )]; 228if ( p . gumbel ) { 229double best = -1.0 ; 230for (int i = 0 ; i < n_keep ; ++ i ) { 231const double r = std:: exp ((double) scaled ( i ) - (double) smx ) / sum / 232host_gumbel_exp ( p . seed , p . counter + (uint64_t) row , (uint32_t) sel_ids [(size_t) i ]); 233if ( r > best ) { best = r ; pick = sel_ids [(size_t) i ]; } 234} 235return pick ; 236} 237const float u = host_philox_uniform ( p . seed , p . counter + (uint64_t) row ); 238double cum = 0.0 ; 239for (int i = 0 ; i < n_keep ; ++ i ) { 240cum += std:: exp ((double) scaled ( i ) - (double) smx ) / sum ; 241if ((double) u < cum ) { pick = sel_ids [(size_t) i ]; break ; } 242} 243return pick ; 244} 245 246// Survivors after the min_p + top_p cuts, in the sampled chain - the quantity an order or a threshold 247// actually changes, used to assert a fixture can SEE the feature before asserting the kernel matches. 248int sampled_cut ( const std::vector < float >& l , const std::vector < int >& hist , const strata::kernels::SamplerParams & p ) { 249auto penal = [ & ](float logit , int count ) { 250if ( count <= 0 ) return logit ; 251if ( logit <= 0.0f ) logit *= p . penalty_repeat ; else logit /= p . penalty_repeat ; 252logit -= (float) count * p . penalty_freq + ( count > 0 ? 1.0f : 0.0f ) * p . penalty_present ; 253return logit ; 254}; 255auto count = [ & ](int v ) { int c = 0 ; for (int h : hist ) if ( h == v ) ++ c ; return c ; }; 256const int nv = (int) l . size (); 257const int KMAX = 64 ; 258const int k = std:: min ( nv , ( p . top_k > 0 && p . top_k < KMAX ) ? p . top_k : KMAX ); 259std::vector < float > sel ; 260std::vector < char > taken ((size_t) nv , 0 ); 261for (int i = 0 ; i < k ; ++ i ) { 262int best = -1 ; float bv = 0 ; 263for (int v = 0 ; v < nv ; ++ v ) { 264if ( taken [(size_t) v ]) continue ; 265const float s = penal ( l [(size_t) v ], count ( v )); 266if ( best < 0 || s > bv ) { best = v ; bv = s ; } 267} 268taken [(size_t) best ] = 1 ; sel . push_back ( bv ); 269} 270int n_minp = (int) sel . size (); 271if ( p . min_p > 0.0f ) { 272const float thresh = sel [ 0 ] + std:: log ( p . min_p ); 273for (int i = 0 ; i < (int) sel . size (); ++ i ) 274if ( sel [(size_t) i ] < thresh ) { n_minp = i ; break ; } 275} 276if ( p . top_p >= 1.0f ) return n_minp ; 277double sum = 0.0 ; 278for (int i = 0 ; i < n_minp ; ++ i ) sum += std:: exp ((double) sel [(size_t) i ] - (double) sel [ 0 ]); 279double cum = 0.0 ; 280int cut = n_minp ; 281for (int i = 0 ; i < n_minp ; ++ i ) { 282cum += std:: exp ((double) sel [(size_t) i ] - (double) sel [ 0 ]) / sum ; 283if ( cum >= (double) p . top_p ) { cut = i + 1 ; break ; } 284} 285if ( cut < p . min_keep ) cut = p . min_keep < n_minp ? p . min_keep : n_minp ; 286return cut ; 287} 288 289// ---- the kernel's own semantics, for the fixtures ---- 290// 291// `sampled_reference` picks the first unpicked logit even when it is -inf or NaN; the kernels never pick either, and 292// a round that finds nothing stores id 0 with a -inf logit (and later rounds treat id 0 as taken, as `sampler_kernel` 293// does). The mirror below follows the kernels, so rows with -inf, NaN, +inf and more requested than finite logits 294// can be pinned exactly. On rows without those it is `sampled_reference`. 295struct SelList { 296std::vector < int > ids ; 297std::vector < float > logit ; 298}; 299 300// The top_k list of `sampler_kernel` for one row: `window` is the counted history (the row's last penalty_last_n). 301SelList mirror_select ( const float * l , int nv , const std::vector < int >& window , const strata::kernels::SamplerParams & p , 302int k ) { 303std::vector < float > s ((size_t) nv ); 304for (int v = 0 ; v < nv ; ++ v ) { 305int c = 0 ; 306for (int h : window ) c += h == v ; 307float x = l [ v ]; 308if ( c > 0 ) { 309if ( x <= 0.0f ) x *= p . penalty_repeat ; else x /= p . penalty_repeat ; 310x -= (float) c * p . penalty_freq + ( c > 0 ? 1.0f : 0.0f ) * p . penalty_present ; 311} 312s [(size_t) v ] = x ; 313} 314SelList out ; 315std::vector < char > taken ((size_t) nv , 0 ); 316for (int i = 0 ; i < k ; ++ i ) { 317int best = nv ; 318float bv = - std::numeric_limits < float > :: infinity (); 319for (int v = 0 ; v < nv ; ++ v ) 320if (! taken [(size_t) v ] && s [(size_t) v ] > bv ) { bv = s [(size_t) v ]; best = v ; } 321const int id = best < nv ? best : 0 ; 322taken [(size_t) id ] = 1 ; 323out . ids . push_back ( id ); 324out . logit . push_back ( bv ); 325} 326return out ; 327} 328 329// The tail of `sampler_kernel` over a list (its first `k` entries): top_p, min_p, temperature, the Philox draw. 330int mirror_pick ( const SelList & sel , int k , const strata::kernels::SamplerParams & p , int row ) { 331int n_keep = k ; 332float mx = sel . logit [ 0 ]; 333for (int i = 1 ; i < k ; ++ i ) mx = std:: fmax ( mx , sel . logit [(size_t) i ]); 334if ( p . top_p < 1.0f ) { 335double sum = 0.0 ; 336for (int i = 0 ; i < k ; ++ i ) sum += std:: exp ((double) sel . logit [(size_t) i ] - (double) mx ); 337double cum = 0.0 ; 338int cut = k ; 339for (int i = 0 ; i < k ; ++ i ) { 340cum += std:: exp ((double) sel . logit [(size_t) i ] - (double) mx ) / sum ; 341if ( cum >= (double) p . top_p ) { cut = i + 1 ; break ; } 342} 343if ( cut < p . min_keep ) cut = p . min_keep < k ? p . min_keep : k ; 344n_keep = cut ; 345} 346if ( p . min_p > 0.0f ) { 347const float thresh = sel . logit [ 0 ] + std:: log ( p . min_p ); 348for (int i = 0 ; i < n_keep ; ++ i ) 349if ( sel . logit [(size_t) i ] < thresh ) { n_keep = i ; break ; } 350} 351const float inv_t = p . temperature > 0.0f ? 1.0f / p . temperature : 0.0f ; 352auto scaled = [ & ](int i ) { return sel . logit [(size_t) i ] * inv_t ; }; 353float smx = scaled ( 0 ); 354for (int i = 1 ; i < n_keep ; ++ i ) smx = std:: fmax ( smx , scaled ( i )); 355double sum = 0.0 ; 356for (int i = 0 ; i < n_keep ; ++ i ) sum += std:: exp ((double) scaled ( i ) - (double) smx ); 357int pick = sel . ids [(size_t) ( n_keep > 0 ? n_keep - 1 : 0 )]; 358if ( p . gumbel ) { 359double best = -1.0 ; 360for (int i = 0 ; i < n_keep ; ++ i ) { 361const double r = std:: exp ((double) scaled ( i ) - (double) smx ) / sum / 362host_gumbel_exp ( p . seed , p . counter + (uint64_t) row , (uint32_t) sel . ids [(size_t) i ]); 363if ( r > best ) { best = r ; pick = sel . ids [(size_t) i ]; } 364} 365return pick ; 366} 367const float u = host_philox_uniform ( p . seed , p . counter + (uint64_t) row ); 368double cum = 0.0 ; 369for (int i = 0 ; i < n_keep ; ++ i ) { 370cum += std:: exp ((double) scaled ( i ) - (double) smx ) / sum ; 371if ((double) u < cum ) { pick = sel . ids [(size_t) i ]; break ; } 372} 373return pick ; 374} 375 376int sampled_k (int top_k , int nv ) { return std:: min ( nv , ( top_k > 0 && top_k < 64 ) ? top_k : 64 ); } 377 378// Rows uploaded once and sampled under many parameter sets: `sample` returns the picks of one launch on `stream` 379// (nullptr: the legacy stream), -1 prefilled as in `run`. 380struct DeviceRows { 381float * l = nullptr ; 382int * h = nullptr ; 383int * o = nullptr ; 384int n_tokens = 0 , nv = 0 , hist_len = 0 ; 385DeviceRows ( const std::vector < float >& logits , int n_tokens_ , const std::vector < int >& hist , int hist_len_ ) 386: n_tokens ( n_tokens_ ), nv ((int) ( logits . size () / (size_t) n_tokens_ )), hist_len ( hist_len_ ) { 387check ( cudaMalloc ( & l , logits . size () * sizeof (float)), "malloc logits" ); 388check ( cudaMalloc ( & o , (size_t) n_tokens * sizeof (int)), "malloc out" ); 389check ( cudaMemcpy ( l , logits . data (), logits . size () * sizeof (float), cudaMemcpyHostToDevice ), "copy" ); 390if ( hist_len > 0 ) { 391check ( cudaMalloc ( & h , hist . size () * sizeof (int)), "malloc hist" ); 392check ( cudaMemcpy ( h , hist . data (), hist . size () * sizeof (int), cudaMemcpyHostToDevice ), "copy hist" ); 393} 394} 395DeviceRows ( const DeviceRows & ) = delete ; 396DeviceRows & operator = ( const DeviceRows & ) = delete ; 397~ DeviceRows () { 398cudaFree ( l ); 399cudaFree ( o ); 400if ( h ) cudaFree ( h ); 401} 402std::vector < int > sample ( const strata::kernels::SamplerParams & p , cudaStream_t stream ) { 403check ( cudaMemset ( o , 0xFF , (size_t) n_tokens * sizeof (int)), "fill out" ); 404strata::kernels:: sample_tokens ( l , n_tokens , nv , h , hist_len , p , o , stream ); 405if ( stream != nullptr ) check ( cudaStreamSynchronize ( stream ), "stream sync" ); 406std::vector < int > got ((size_t) n_tokens ); 407check ( cudaMemcpy ( got . data (), o , got . size () * sizeof (int), cudaMemcpyDeviceToHost ), "back" ); 408return got ; 409} 410}; 411 412// The counted window of row t: the last min(penalty_last_n, hist_len) entries (none without penalties). 413std::vector < int > window_of ( const std::vector < int >& hist , int hist_len , int t , int last_n ) { 414if ( hist_len <= 0 || last_n <= 0 ) return {}; 415const int h = std:: min ( last_n , hist_len ); 416const int * row = hist . data () + (size_t) t * hist_len ; 417return std:: vector < int > ( row + ( hist_len - h ), row + hist_len ); 418} 419 420// `--bench`: the sampled path alone at the engine's vocabulary, per call, on the path the environment selects. 421void bench_sampled () { 422const int NV = 248320 ; 423cudaStream_t s = nullptr ; 424check ( cudaStreamCreate ( & s ), "stream" ); 425std::mt19937 rng ( 20 ); 426std::normal_distribution < float > g ( 0.0f , 3.0f ); 427for (int T : { 1 , 4 , 8 }) { 428std::vector < float > l ((size_t) NV * T ); 429for (auto & v : l ) v = g ( rng ); 430float * d_l = nullptr ; 431int * d_o = nullptr ; 432check ( cudaMalloc ( & d_l , l . size () * sizeof (float)), "bench logits" ); 433check ( cudaMalloc ( & d_o , (size_t) T * sizeof (int)), "bench out" ); 434check ( cudaMemcpy ( d_l , l . data (), l . size () * sizeof (float), cudaMemcpyHostToDevice ), "bench copy" ); 435for (int k : { 20 , 64 }) { 436strata::kernels::SamplerParams p ; 437p . top_k = k ; p . top_p = 0.95f ; p . temperature = 0.7f ; p . seed = 1 ; 438for (int w = 0 ; w < 3 ; ++ w ) strata::kernels:: sample_tokens ( d_l , T , NV , nullptr , 0 , p , d_o , s ); 439check ( cudaStreamSynchronize ( s ), "bench warmup" ); 440cudaEvent_t e0 , e1 ; 441check ( cudaEventCreate ( & e0 ), "event" ); 442check ( cudaEventCreate ( & e1 ), "event" ); 443const int iters = 50 ; 444check ( cudaEventRecord ( e0 , s ), "record" ); 445for (int it = 0 ; it < iters ; ++ it ) { 446p . counter = (uint64_t) it ; 447strata::kernels:: sample_tokens ( d_l , T , NV , nullptr , 0 , p , d_o , s ); 448} 449check ( cudaEventRecord ( e1 , s ), "record" ); 450check ( cudaEventSynchronize ( e1 ), "bench sync" ); 451float ms = 0.0f ; 452check ( cudaEventElapsedTime ( & ms , e0 , e1 ), "elapsed" ); 453std:: printf ( " bench: n_vocab %d, rows %d, top_k %2d, top_p 0.95: %8.1f us per call\n" , NV , T , k , 4541000.0 * (double) ms / iters ); 455cudaEventDestroy ( e0 ); 456cudaEventDestroy ( e1 ); 457} 458cudaFree ( d_l ); 459cudaFree ( d_o ); 460} 461cudaStreamDestroy ( s ); 462} 463 464} // namespace 465 466int main (int argc , char ** argv ) { 467bool selftest = false, bench = false; 468for (int i = 1 ; i < argc ; ++ i ) { 469if (std:: string ( argv [ i ]) == "--selftest" ) selftest = true; 470else if (std:: string ( argv [ i ]) == "--bench" ) bench = true; 471else { std:: fprintf ( stderr , "usage: sampler_parity [--selftest] [--bench]\n" ); return 2 ; } 472} 473{ 474// the sampled path under test; ctest runs this binary once per path 475auto on = []( const char * n ) { const char * e = std:: getenv ( n ); return e && * e && std:: strcmp ( e , "0" ) != 0 ; }; 476std:: printf ( " sampled path: %s\n" , on ( "STRATA_OLD_SAMPLER" ) ? "sampler_kernel (STRATA_OLD_SAMPLER)" 477: on ( "STRATA_SAMPLER_ONE_BLOCK" ) ? "one block (STRATA_SAMPLER_ONE_BLOCK)" 478: "split top_k (default)" ); 479} 480if ( bench ) { 481bench_sampled (); 482return 0 ; 483} 484int bad = 0 ; 485const int NV = 512 , NT = 4 ; 486 487// Request bias affects every target row, including greedy; omission leaves logits and the default pick intact. 488// Compare against an independently pre-biased input through each ctest sampler implementation. 489{ 490std::vector < float > l (NV * NT ), bias ( NV , 0.0f ), adjusted ; 491for (int t = 0 ; t < NT ; ++ t ) 492for (int v = 0 ; v < NV ; ++ v ) l [ t * NV + v ] = float( v % 17 ) / 4 ; 493l [ 0 ] = 50 ; 494bias [ 0 ] = - std::numeric_limits < float > :: infinity (); 495bias [ 7 ] = 20 ; 496bias [ 16 ] = -9 ; 497adjusted = l ; 498for (int t = 0 ; t < NT ; ++ t ) 499for (int v = 0 ; v < NV ; ++ v ) adjusted [ t * NV + v ] += bias [ v ]; 500float * db = nullptr ; 501check ( cudaMalloc ( & db , NV * sizeof (float)), "bias malloc" ); 502check ( cudaMemcpy ( db , bias . data (), NV * sizeof (float), cudaMemcpyHostToDevice ), "bias upload" ); 503std::vector < int > hist ( NT * 4 , 7 ); 504DeviceRows raw ( l , NT , hist , 4 ), expected ( adjusted , NT , hist , 4 ); 505for (bool greedy : {true, false}) for (bool penalty : {false, true}) { 506strata::kernels::SamplerParams p ; 507p . greedy = greedy ; p . temperature = greedy ? 0 : 0.8f ; p . seed = 71 ; p . top_k = 16 ; 508if ( penalty ) { p . penalty_last_n = 4 ; p . penalty_freq = 3 ; p . penalty_repeat = 1.1f ; } 509const auto want = expected . sample ( p , nullptr ); 510p . logit_bias = db ; 511const auto got = raw . sample ( p , nullptr ); 512if ( got != want || std:: find ( got . begin (), got . end (), 0 ) != got . end ()) ++ bad ; 513p . logit_bias = nullptr ; 514DeviceRows plain ( l , NT , hist , 4 ); 515if ( raw . sample ( p , nullptr ) != plain . sample ( p , nullptr )) ++ bad ; 516} 517std::vector < float > unchanged ( l . size ()); 518check ( cudaMemcpy ( unchanged . data (), raw . l , l . size () * sizeof (float), cudaMemcpyDeviceToHost ), "raw logits" ); 519if ( unchanged != l ) ++ bad ; 520// The reporter's vocabulary scale, with only one permitted token: masked entries cannot win top-k tails. 521const int vocab = 248320 ; 522std::vector < float > large ( vocab , 100 ), bans ( vocab , - std::numeric_limits < float > :: infinity ()); 523bans [ 109266 ] = 0 ; large [ 109266 ] = -50 ; 524cudaFree ( db ); 525check ( cudaMalloc ( & db , vocab * sizeof (float)), "large bias malloc" ); 526check ( cudaMemcpy ( db , bans . data (), bans . size () * sizeof (float), cudaMemcpyHostToDevice ), "large bias upload" ); 527DeviceRows many ( large , 1 , {}, 0 ); 528for (bool greedy : {true, false}) { 529strata::kernels::SamplerParams p ; p . greedy = greedy ; p . logit_bias = db ; 530if ( many . sample ( p , nullptr ) != std::vector < int > { 109266 }) ++ bad ; 531} 532cudaFree ( db ); 533} 534 535// ---- fixture 1: plain greedy. top_k = 0 (disabled), top_p = 1 (disabled), T = 1 -> argmax. 536{ 537strata::kernels::SamplerParams p ; p . top_k = 0 ; p . top_p = 1.0f ; p . temperature = 1.0f ; p . greedy = true; 538std::mt19937 rng ( 3 ); std::normal_distribution < float > g ( 0.0f , 1.0f ); 539std::vector < float > l ((size_t) NV * NT ); 540for (auto & v : l ) v = g ( rng ); 541std::vector < int > want ((size_t) NT ); 542for (int t = 0 ; t < NT ; ++ t ) want [(size_t) t ] = reference_pick ({ l . begin () + (size_t) t * NV , l . begin () + (size_t) ( t + 1 ) * NV }, p , false); 543bad += run ( "greedy argmax" , l , NT , p , want ); 544} 545 546// ---- fixture 2: THE ORDER FIXTURE. T = 0.5 sharpens the distribution enough that top_p = 0.5 cuts 547// differently before and after the scaling, and the two orders then pick DIFFERENT tokens. 548{ 549strata::kernels::SamplerParams p ; p . top_k = 0 ; p . top_p = 0.5f ; p . temperature = 0.5f ; 550p . min_keep = 1 ; p . greedy = true; 551std::vector < float > l ((size_t) NV * NT , -1000.0f ); 552for (int t = 0 ; t < NT ; ++ t ) { 553// a flat-ish head so the cumulative mass crosses 0.5 inside it, and one clear leader 554l [(size_t) t * NV + 0 ] = 3.0f ; 555for (int v = 1 ; v < 8 ; ++ v ) l [(size_t) t * NV + v ] = 2.6f - 0.05f * (float) v ; 556} 557std::vector < int > want ((size_t) NT ), other ((size_t) NT ); 558for (int t = 0 ; t < NT ; ++ t ) { 559const std::vector < float > row ( l . begin () + (size_t) t * NV , l . begin () + (size_t) ( t + 1 ) * NV ); 560want [(size_t) t ] = reference_pick ( row , p , false); // the SPECIFIED order 561other [(size_t) t ] = reference_pick ( row , p , true); // temperature first 562} 563// If the two orders agree on this fixture the test cannot see the order, and saying "the kernel 564// matches the spec" would be vacuous. 565// GREEDY CANNOT SEE THE ORDER, and saying otherwise would be a vacuous check: no filter removes the 566// global argmax, and temperature is monotonic, so the greedy pick is order-independent by 567// construction. What the order changes is the top_p CUT, so the fixture is asserted to be 568// order-SENSITIVE at the cut, which is a property of the fixture rather than of the kernel. 569int cut_spec = 0 , cut_alt = 0 ; 570for (int t = 0 ; t < NT ; ++ t ) { 571const std::vector < float > row ( l . begin () + (size_t) t * NV , l . begin () + (size_t) ( t + 1 ) * NV ); 572cut_spec += reference_cut ( row , p , false); 573cut_alt += reference_cut ( row , p , true); 574} 575const bool distinguishable = ( cut_spec != cut_alt ); 576std:: printf ( " %-34s %s (survivors: spec %d, temp-first %d)\n" , "order is observable on this fixture" , 577distinguishable ? "yes" : "*** NO - THE FIXTURE CANNOT SEE THE ORDER ***" , cut_spec , 578cut_alt ); 579if (! distinguishable ) ++ bad ; 580// greedy is still checked here, but as an ARGMAX check, not an order check 581bad += run ( "greedy over this fixture" , l , NT , p , want ); 582} 583 584// ---- fixture 3: greedy consumes NO random number. Two runs with different seeds must agree, or the 585// seeded streams diverge between greedy and sampled runs - which docs/sampling.md §3 calls out. 586{ 587strata::kernels::SamplerParams a ; a . top_k = 20 ; a . top_p = 0.95f ; a . temperature = 1.0f ; a . greedy = true; a . seed = 1 ; 588strata::kernels::SamplerParams b = a ; b . seed = 999999 ; 589std::mt19937 rng ( 5 ); std::normal_distribution < float > g ( 0.0f , 1.0f ); 590std::vector < float > l ((size_t) NV * NT ); 591for (auto & v : l ) v = g ( rng ); 592std::vector < int > wa ((size_t) NT ); 593for (int t = 0 ; t < NT ; ++ t ) wa [(size_t) t ] = reference_pick ({ l . begin () + (size_t) t * NV , l . begin () + (size_t) ( t + 1 ) * NV }, a , false); 594float * d_l = nullptr ; int * d_a = nullptr , * d_b = nullptr ; 595check ( cudaMalloc ( & d_l , l . size () * sizeof (float)), "m1" ); 596check ( cudaMalloc ( & d_a , (size_t) NT * sizeof (int)), "m2" ); 597check ( cudaMalloc ( & d_b , (size_t) NT * sizeof (int)), "m3" ); 598check ( cudaMemcpy ( d_l , l . data (), l . size () * sizeof (float), cudaMemcpyHostToDevice ), "c1" ); 599strata::kernels:: sample_tokens ( d_l , NT , NV , nullptr , 0 , a , d_a , nullptr ); 600strata::kernels:: sample_tokens ( d_l , NT , NV , nullptr , 0 , b , d_b , nullptr ); 601std::vector < int > ga ((size_t) NT ), gb ((size_t) NT ); 602check ( cudaMemcpy ( ga . data (), d_a , ga . size () * sizeof (int), cudaMemcpyDeviceToHost ), "g1" ); 603check ( cudaMemcpy ( gb . data (), d_b , gb . size () * sizeof (int), cudaMemcpyDeviceToHost ), "g2" ); 604int mismatch = 0 , wrong = 0 ; 605for (int t = 0 ; t < NT ; ++ t ) { 606if ( ga [(size_t) t ] != gb [(size_t) t ]) ++ mismatch ; 607if ( ga [(size_t) t ] != wa [(size_t) t ]) ++ wrong ; 608} 609std:: printf ( " %-34s %s (seed-independent: %d differ; vs reference: %d wrong)\n" , 610"greedy ignores the seed" , (! mismatch && ! wrong ) ? "matches" : "*** WRONG ***" , mismatch , 611wrong ); 612bad += mismatch + wrong ; 613cudaFree ( d_l ); cudaFree ( d_a ); cudaFree ( d_b ); 614} 615 616 617// ---- fixture 4: PENALTIES. Two sub-cases, each built so the rule it tests decides the answer. 618{ 619// host reference for the penalty stage, transcribed from llama_sampler_penalties_apply 620auto penal = [](float logit , int count , const strata::kernels::SamplerParams & p ) { 621if ( count <= 0 ) return logit ; 622if ( logit <= 0.0f ) logit *= p . penalty_repeat ; else logit /= p . penalty_repeat ; 623logit -= (float) count * p . penalty_freq + ( count > 0 ? 1.0f : 0.0f ) * p . penalty_present ; 624return logit ; 625}; 626auto pick = [ & ]( const std::vector < float >& l , const std::vector < int >& hist , 627const strata::kernels::SamplerParams & p , bool divide_unconditionally ) { 628int best = 0 ; float bv = 0 ; bool first = true; 629for (int v = 0 ; v < (int) l . size (); ++ v ) { 630int c = 0 ; for (int h : hist ) if ( h == v ) ++ c ; 631float s ; 632if ( divide_unconditionally && c > 0 ) { 633s = l [(size_t) v ] / p . penalty_repeat 634- (float) c * p . penalty_freq - ( c > 0 ? 1.0f : 0.0f ) * p . penalty_present ; 635} else { 636s = penal ( l [(size_t) v ], c , p ); 637} 638if ( first || s > bv ) { bv = s ; best = v ; first = false; } 639} 640return best ; 641}; 642 643const int NV2 = 8 , NT2 = 2 ; 644strata::kernels::SamplerParams p ; p . top_k = 0 ; p . top_p = 1.0f ; p . temperature = 1.0f ; 645p . greedy = true; p . penalty_last_n = 4 ; p . penalty_repeat = 2.0f ; 646 647// A: ALL logits negative, so the multiply-or-divide rule decides the argmax 648std::vector < float > la ((size_t) NV2 * NT2 , -8.0f ); 649for (int t = 0 ; t < NT2 ; ++ t ) { 650la [(size_t) t * NV2 + 0 ] = -1.0f ; // in the history -> penalised 651la [(size_t) t * NV2 + 1 ] = -1.2f ; // not penalised -> should win 652} 653std::vector < int > hist_a ((size_t) NT2 * 4 , -1 ); 654for (int t = 0 ; t < NT2 ; ++ t ) hist_a [(size_t) t * 4 + 0 ] = 0 ; 655std::vector < int > want_a ((size_t) NT2 ), alt_a ((size_t) NT2 ); 656for (int t = 0 ; t < NT2 ; ++ t ) { 657const std::vector < float > row ( la . begin () + (size_t) t * NV2 , la . begin () + (size_t) ( t + 1 ) * NV2 ); 658const std::vector < int > h ( hist_a . begin () + (size_t) t * 4 , hist_a . begin () + (size_t) ( t + 1 ) * 4 ); 659want_a [(size_t) t ] = pick ( row , h , p , false); 660alt_a [(size_t) t ] = pick ( row , h , p , true); // divide unconditionally 661} 662const bool A_visible = want_a [ 0 ] != alt_a [ 0 ]; 663std:: printf ( " %-34s %s (multiply-rule %d, divide-always %d)\n" , 664"multiply-or-divide is observable" , A_visible ? "yes" : "*** NO ***" , want_a [ 0 ], 665alt_a [ 0 ]); 666if (! A_visible ) ++ bad ; 667else bad += run ( "penalties: repeat on negatives" , la , NT2 , p , want_a , hist_a , 4 ); 668 669// B: the PRESENCE penalty is a boolean, so two occurrences cost the same as one. The runner's margin 670// is inside the difference between one and two applications. 671std::vector < float > lb ((size_t) NV2 * NT2 , -8.0f ); 672for (int t = 0 ; t < NT2 ; ++ t ) { 673lb [(size_t) t * NV2 + 0 ] = 5.0f ; // seen twice -> penalised ONCE (presence) + freq*2 674lb [(size_t) t * NV2 + 1 ] = 3.4f ; // unseen 675} 676std::vector < int > hist_b ((size_t) NT2 * 4 , -1 ); 677for (int t = 0 ; t < NT2 ; ++ t ) { 678hist_b [(size_t) t * 4 + 0 ] = 0 ; 679hist_b [(size_t) t * 4 + 1 ] = 0 ; // twice 680} 681strata::kernels::SamplerParams q = p ; q . penalty_present = 1.5f ; q . penalty_freq = 0.0f ; 682std::vector < int > want_b ((size_t) NT2 ); 683for (int t = 0 ; t < NT2 ; ++ t ) { 684const std::vector < float > row ( lb . begin () + (size_t) t * NV2 , lb . begin () + (size_t) ( t + 1 ) * NV2 ); 685const std::vector < int > h ( hist_b . begin () + (size_t) t * 4 , hist_b . begin () + (size_t) ( t + 1 ) * 4 ); 686want_b [(size_t) t ] = pick ( row , h , q , false); 687} 688std:: printf ( " %-34s want token %d (with present=1.5, token 0 goes 5.0/2 - 1.5 = 1.0 vs token 1 at " 689"3.4)\n" , "presence penalty is a boolean" , want_b [ 0 ]); 690bad += run ( "penalties: presence is boolean" , lb , NT2 , q , want_b , hist_b , 4 ); 691} 692 693// ---- fixture 5: TEMPERATURE 0 MUST STILL RETURN THE ARGMAX. Regression test for a real bug. 694// 695// The greedy branch used to read `apply_penalties(l[v] * inv_t, ...)`. `inv_t` is 0.0f whenever 696// temperature <= 0, so at temperature 0 EVERY logit became 0.0f and the argmax returned index 0 - the 697// sampler emitted token 0 forever, whatever the model predicted. OpenAI clients send `temperature: 0` 698// for greedy decoding, so this was reachable from any ordinary client. 699// 700// It survived because EVERY other greedy fixture in this file sets temperature = 1.0f, where inv_t = 1.0 701// and the extra multiply is harmless. The bug needs temperature <= 0 to appear, and no fixture used it. 702// The fixture below makes token 0 the WORST token in every row, so returning 0 is unambiguously wrong. 703{ 704const int NV3 = 512 , NT3 = 4 ; 705std::vector < float > l ((size_t) NV3 * NT3 , -5.0f ); 706std::vector < int > want ((size_t) NT3 ); 707for (int t = 0 ; t < NT3 ; ++ t ) { 708const int best = 100 + t ; // the argmax is never token 0 709l [(size_t) t * NV3 + best ] = 3.0f ; 710l [(size_t) t * NV3 + 0 ] = -9.0f ; // token 0 is the worst in the row 711want [(size_t) t ] = best ; 712} 713strata::kernels::SamplerParams p0 ; 714p0 . top_k = 0 ; p0 . top_p = 1.0f ; p0 . temperature = 0.0f ; p0 . greedy = false; 715bad += run ( "T=0 greedy=false is the argmax" , l , NT3 , p0 , want ); 716 717strata::kernels::SamplerParams p1 = p0 ; p1 . greedy = true; 718bad += run ( "T=0 greedy=true is the argmax" , l , NT3 , p1 , want ); 719 720strata::kernels::SamplerParams p2 = p0 ; p2 . greedy = true; p2 . temperature = 1.0f ; 721bad += run ( "T=1 greedy=true is the argmax" , l , NT3 , p2 , want ); 722} 723 724// ---- fixture 6: PENALTIES IN THE SAMPLED CHAIN. Fixture 4 pins the greedy (argmax) path; the sampled 725// chain gets its own reference (the full chain with the host Philox) and its own observability check: with 726// the penalties on, the history row's favourite must LOSE a pick it would win penalty-free. 727{ 728const int NV2 = 8 , NT2 = 2 ; 729strata::kernels::SamplerParams p ; 730p . top_k = 5 ; p . top_p = 0.9f ; p . temperature = 0.8f ; p . seed = 9 ; p . counter = 0 ; 731p . penalty_last_n = 4 ; p . penalty_repeat = 3.0f ; p . penalty_freq = 0.2f ; p . penalty_present = 0.6f ; 732 733std::vector < float > l ((size_t) NV2 * NT2 , -8.0f ); 734std::vector < int > hist ((size_t) NT2 * 4 , -1 ); 735for (int t = 0 ; t < NT2 ; ++ t ) { 736float * row = l . data () + (size_t) t * NV2 ; 737row [ 0 ] = 9.0f ; row [ 1 ] = 4.5f ; row [ 2 ] = 4.4f ; row [ 3 ] = 4.3f ; // token 0 leads clean (9 vs 4.5) 738hist [(size_t) t * 4 + 0 ] = 0 ; // and falls to 2.2/2.0 penalised 739hist [(size_t) t * 4 + 1 ] = t == 1 ? 0 : -1 ; // (repeat 3, freq, presence) 740} 741std::vector < int > want ((size_t) NT2 ), clean ((size_t) NT2 ); 742strata::kernels::SamplerParams clean_p = p ; 743clean_p . penalty_last_n = 0 ; clean_p . penalty_repeat = 1.0f ; 744clean_p . penalty_freq = 0.0f ; clean_p . penalty_present = 0.0f ; 745for (int t = 0 ; t < NT2 ; ++ t ) { 746const std::vector < float > row ( l . begin () + (size_t) t * NV2 , l . begin () + (size_t) ( t + 1 ) * NV2 ); 747const std::vector < int > h ( hist . begin () + (size_t) t * 4 , hist . begin () + (size_t) ( t + 1 ) * 4 ); 748want [(size_t) t ] = sampled_reference ( row , h , p , t ); 749clean [(size_t) t ] = sampled_reference ( row , h , clean_p , t ); 750} 751const bool visible = want [ 0 ] != clean [ 0 ] || want [ 1 ] != clean [ 1 ]; 752std:: printf ( " %-34s %s (penalised picks %d/%d, clean %d/%d)\n" , 753"sampled penalties are observable" , visible ? "yes" : "*** NO ***" , want [ 0 ], want [ 1 ], 754clean [ 0 ], clean [ 1 ]); 755if (! visible ) ++ bad ; 756else bad += run ( "sampled chain: penalties + top_k/p" , l , NT2 , p , want , hist , 4 ); 757} 758 759// ---- fixture 7: MIN_P. The cut is a PREFIX of the descending top_k list (logit >= max + log(min_p)), 760// so the fixture asserts the survivor count moves with the threshold (the observability half) and that 761// the kernel's pick equals the reference's through the full sampled chain (the correctness half). 762{ 763const int NV3 = 8 , NT3 = 2 ; 764std::vector < float > l ((size_t) NV3 * NT3 , -8.0f ); 765for (int t = 0 ; t < NT3 ; ++ t ) { 766float * row = l . data () + (size_t) t * NV3 ; 767row [ 0 ] = 4.0f ; row [ 1 ] = 3.5f ; row [ 2 ] = 3.2f ; row [ 3 ] = 3.1f ; // gaps keep the cut off the 768row [ 4 ] = 2.0f ; // logf/rounding knife edge 769} 770strata::kernels::SamplerParams base ; 771base . top_k = 6 ; base . top_p = 1.0f ; base . temperature = 0.9f ; base . seed = 77 ; 772 773int c0 = 0 , c05 = 0 , c09 = 0 ; 774for (int t = 0 ; t < NT3 ; ++ t ) { 775const std::vector < float > row ( l . begin () + (size_t) t * NV3 , l . begin () + (size_t) ( t + 1 ) * NV3 ); 776strata::kernels::SamplerParams q = base ; q . min_p = 0.0f ; 777c0 += sampled_cut ( row , {}, q ); 778q . min_p = 0.5f ; c05 += sampled_cut ( row , {}, q ); 779q . min_p = 0.9f ; c09 += sampled_cut ( row , {}, q ); 780} 781const bool visible = c0 > c05 && c05 > c09 && c09 >= NT3 ; 782std:: printf ( " %-34s %s (survivors: min_p 0 -> %d, 0.5 -> %d, 0.9 -> %d)\n" , 783"min_p cut is observable" , visible ? "yes" : "*** NO ***" , c0 , c05 , c09 ); 784if (! visible ) ++ bad ; 785 786for (float mp : { 0.0f , 0.5f , 0.9f }) { 787strata::kernels::SamplerParams q = base ; q . min_p = mp ; 788std::vector < int > want ((size_t) NT3 ); 789for (int t = 0 ; t < NT3 ; ++ t ) { 790const std::vector < float > row ( l . begin () + (size_t) t * NV3 , l . begin () + (size_t) ( t + 1 ) * NV3 ); 791want [(size_t) t ] = sampled_reference ( row , {}, q , t ); 792} 793char name [ 64 ]; 794std:: snprintf ( name , sizeof name , "sampled chain: min_p=%.1f" , (double) mp ); 795bad += run ( name , l , NT3 , q , want ); 796} 797} 798 799// ---- fixture 8: THE PENALTY WINDOW IS THE TAIL. With an 8-entry history and penalty_last_n = 4, only 800// the LAST four entries count: a token punished in the old half must come back to full strength, and one 801// punished in the tail half stays down. The reference counts the same tail; the observability check runs 802// the reference once more WITHOUT the clamp (counting all 8) and requires the picks to differ. 803{ 804const int NV4 = 8 ; 805strata::kernels::SamplerParams p ; 806p . top_k = 0 ; p . top_p = 1.0f ; p . temperature = 1.0f ; p . greedy = true; 807p . penalty_last_n = 4 ; p . penalty_repeat = 3.0f ; p . penalty_freq = 0.3f ; p . penalty_present = 0.5f ; 808 809std::vector < float > l ((size_t) NV4 , -8.0f ); 810l [ 0 ] = 6.0f ; l [ 3 ] = 6.5f ; // token 0 leads clean; token 3 is the tail offender 811std::vector < int > hist = { 0 , 0 , 0 , 0 , 3 , 3 , 3 , 3 }; // token 0 old (out), token 3 in the tail 812 813auto pick_clamped = [ & ](bool clamp ) { 814int best = 0 ; float bv = 0 ; bool first = true; 815for (int v = 0 ; v < NV4 ; ++ v ) { 816int c = 0 ; 817for (int i = 0 ; i < ( clamp ? 4 : 8 ); ++ i ) if ( hist [(size_t) ( 8 - ( clamp ? 4 : 8 ) + i )] == v ) ++ c ; 818float logit = l [(size_t) v ]; 819if ( c > 0 ) { logit = logit <= 0.0f ? logit * p . penalty_repeat : logit / p . penalty_repeat ; 820logit -= (float) c * p . penalty_freq + p . penalty_present ; } 821if ( first || logit > bv ) { bv = logit ; best = v ; first = false; } 822} 823return best ; 824}; 825const int want = pick_clamped (true), unclamped = pick_clamped (false); 826const bool visible = want != unclamped ; 827std:: printf ( " %-34s %s (clamped pick %d, full-history pick %d)\n" , 828"penalty window clamp is observable" , visible ? "yes" : "*** NO ***" , want , unclamped ); 829if (! visible ) ++ bad ; 830else bad += run ( "penalty window: tail only" , { l . begin (), l . end ()}, 1 , p , { want }, hist , 8 ); 831} 832 833// ---- fixture 9: ONE PENALTIES STAGE (issue #53), against an independently computed distribution, not the 834// reference above (which had copied the kernel's mistake). Two tokens with equal logits, token 0 in the 835// history, presence penalty 1.5, temperature 0.7: llama.cpp's chain gives token 0 the logit (0 - 1.5) / 0.7, 836// P = 1 / (1 + exp(1.5 / 0.7)) = 0.1050; a second penalty after the temperature made it 0.0255. Over 8,000 837// draws the kernel's share of token 0 must be near 0.105 (4 sigma = 0.014), and its picks must equal the 838// reference's draw for draw. 839{ 840const int NT9 = 8000 ; 841strata::kernels::SamplerParams p ; 842p . top_k = 2 ; p . top_p = 1.0f ; p . min_p = 0.0f ; p . temperature = 0.7f ; p . seed = 53 ; p . counter = 0 ; 843p . penalty_last_n = 1 ; p . penalty_repeat = 1.0f ; p . penalty_freq = 0.0f ; p . penalty_present = 1.5f ; 844std::vector < float > l ((size_t) 2 * NT9 , 0.0f ); 845std::vector < int > hist ((size_t) NT9 , 0 ); 846std::vector < int > want ((size_t) NT9 ); 847int zeros = 0 ; 848for (int t = 0 ; t < NT9 ; ++ t ) { 849want [(size_t) t ] = sampled_reference ({ 0.0f , 0.0f }, { 0 }, p , t ); 850zeros += want [(size_t) t ] == 0 ; 851} 852const double expect = 1.0 / ( 1.0 + std:: exp ( 1.5 / 0.7 )), share = (double) zeros / NT9 ; 853const bool near = std:: fabs ( share - expect ) < 0.014 ; 854std:: printf ( " %-34s %s (token 0 drawn %.4f of %d, expected %.4f; twice-penalised would be 0.0255)\n" , 855"one penalties stage (#53)" , near ? "yes" : "*** NO ***" , share , NT9 , expect ); 856if (! near ) ++ bad ; 857bad += run ( "sampled chain: #53's example" , l , NT9 , p , want , hist , 1 ); 858} 859 860// ---- fixture 10: TOP_P BEFORE MIN_P (llama.cpp's order). Probabilities 0.4 / 0.3 / 0.2 / 0.1, top_p 0.75, 861// min_p 0.3 (keeps p >= 0.12): top_p over all four keeps three (0.4 + 0.3 < 0.75 <= 0.9) and min_p keeps them; 862// min_p first would drop 0.1, renormalise, and top_p would then stop at two (0.444 + 0.333 >= 0.75). So token 863// 2 must be drawn sometimes - never in the old order - and every pick must equal the reference's. 864{ 865const int NT10 = 256 ; 866strata::kernels::SamplerParams p ; 867p . top_k = 4 ; p . top_p = 0.75f ; p . min_p = 0.3f ; p . temperature = 1.0f ; p . seed = 10 ; p . counter = 0 ; 868const float lp [ 4 ] = {std:: log ( 0.4f ), std:: log ( 0.3f ), std:: log ( 0.2f ), std:: log ( 0.1f )}; 869std::vector < float > row = { lp [ 0 ], lp [ 1 ], lp [ 2 ], lp [ 3 ], -30.0f , -30.0f , -30.0f , -30.0f }; 870std::vector < float > l ; 871for (int t = 0 ; t < NT10 ; ++ t ) l . insert ( l . end (), row . begin (), row . end ()); 872std::vector < int > want ((size_t) NT10 ); 873int twos = 0 ; 874for (int t = 0 ; t < NT10 ; ++ t ) { 875want [(size_t) t ] = sampled_reference ( row , {}, p , t ); 876twos += want [(size_t) t ] == 2 ; 877} 878std:: printf ( " %-34s %s (token 2 drawn %d of %d times)\n" , "top_p before min_p is observable" , 879twos > 0 ? "yes" : "*** NO ***" , twos , NT10 ); 880if ( twos == 0 ) ++ bad ; 881bad += run ( "sampled chain: top_p then min_p" , l , NT10 , p , want ); 882} 883 884// ---- fixture 11: A STALE HISTORY WITH last_n = 0 IS INERT (PR #59). A caller can hand over a history buffer 885// from a previous penalised request while this request disables the penalties - the run must equal the 886// no-history run in both kernels, and the bitmap the launch did not size must stay untouched. 887{ 888std::mt19937 rng ( 11 ); std::normal_distribution < float > g ( 0.0f , 1.0f ); 889std::vector < float > l ((size_t) NV * NT ); 890for (auto & v : l ) v = g ( rng ); 891std::vector < int > hist ((size_t) NT * 8 , -1 ); 892for (int t = 0 ; t < NT ; ++ t ) hist [(size_t) t * 8 ] = 3 ; 893 894strata::kernels::SamplerParams p ; 895p . top_k = 20 ; p . top_p = 0.95f ; p . temperature = 0.8f ; p . seed = 5 ; 896std::vector < int > want ((size_t) NT ); 897for (int t = 0 ; t < NT ; ++ t ) 898want [(size_t) t ] = sampled_reference ({ l . begin () + (size_t) t * NV , 899l . begin () + (size_t) ( t + 1 ) * NV }, {}, p , t ); 900bad += run ( "stale history, last_n=0 (sampled)" , l , NT , p , want , hist , 8 ); 901 902strata::kernels::SamplerParams gp = p ; gp . greedy = true; gp . top_k = 0 ; gp . top_p = 1.0f ; 903std::vector < int > gwant ((size_t) NT ); 904for (int t = 0 ; t < NT ; ++ t ) 905gwant [(size_t) t ] = reference_pick ({ l . begin () + (size_t) t * NV , 906l . begin () + (size_t) ( t + 1 ) * NV }, gp , false); 907bad += run ( "stale history, last_n=0 (greedy)" , l , NT , gp , gwant , hist , 8 ); 908} 909 910// ---- fixture 12: ONE HISTORY PER ROW (engine 0.1.19). A verify window samples T rows, and row t's pick 911// follows the drafts 1..t: its penalties must count them. The engine used to stage row 0 alone, so rows 912// 1..T-1 read slots nobody wrote. Here every row gets `penalty_rows`' history and is pinned against a 913// per-row scalar reference; the fixture first asserts it can SEE the difference - with row 0's history 914// copied to every row (the nearest well-defined stand-in for the old staging) some row must pick differently. 915// Row t's own newest token (window[t]) is its favourite by a margin the presence penalty overturns. 916{ 917auto greedy_pen = []( const std::vector < float >& l , const std::vector < int >& hist , 918const strata::kernels::SamplerParams & p ) { 919int best = 0 ; float bv = 0 ; bool first = true; 920for (int v = 0 ; v < (int) l . size (); ++ v ) { 921int c = 0 ; for (int h : hist ) if ( h == v ) ++ c ; 922float s = l [(size_t) v ]; 923if ( c > 0 ) { 924if ( s <= 0.0f ) s *= p . penalty_repeat ; else s /= p . penalty_repeat ; 925s -= (float) c * p . penalty_freq + p . penalty_present ; 926} 927if ( first || s > bv ) { bv = s ; best = v ; first = false; } 928} 929return best ; 930}; 931std::mt19937 rng ( 12 ); std::normal_distribution < float > g ( 0.0f , 1.0f ); 932const int TAIL = 5000 ; // longer than the widest window below 933std::vector < int32_t > tail ((size_t) TAIL ); 934for (auto & v : tail ) v = (int32_t) ( rng () % NV ); 935int observable = 0 , rows_checked = 0 ; 936for (int T : { 1 , 2 , 4 , 8 }) { 937for (int H : { 1 , 64 , 1024 , 4096 }) { 938std::vector < int32_t > window ((size_t) T ); 939for (int t = 0 ; t < T ; ++ t ) window [(size_t) t ] = (int32_t) ( 100 + 37 * t ); // distinct, in range 940std::vector < int32_t > rows ((size_t) T * H ); 941strata::kernels:: penalty_rows ( tail . data (), TAIL , window . data (), T , H , rows . data ()); 942std::vector < float > l ((size_t) T * NV ); 943for (auto & v : l ) v = g ( rng ); 944for (int t = 0 ; t < T ; ++ t ) l [(size_t) t * NV + window [(size_t) t ]] = 5.0f ; 945strata::kernels::SamplerParams gp ; 946gp . greedy = true; gp . temperature = 0.0f ; gp . top_k = 0 ; gp . top_p = 1.0f ; 947gp . penalty_last_n = H ; gp . penalty_present = 4.0f ; 948strata::kernels::SamplerParams sp2 ; 949sp2 . top_k = 20 ; sp2 . top_p = 0.9f ; sp2 . temperature = 0.7f ; sp2 . seed = 1000 + (uint64_t) H ; 950sp2 . counter = 77 ; sp2 . penalty_last_n = H ; sp2 . penalty_present = 4.0f ; sp2 . penalty_repeat = 1.1f ; 951std::vector < int > gwant ((size_t) T ), swant ((size_t) T ), rows_int ( rows . begin (), rows . end ()); 952for (int t = 0 ; t < T ; ++ t ) { 953const std::vector < float > lr ( l . begin () + (size_t) t * NV , l . begin () + (size_t) ( t + 1 ) * NV ); 954const std::vector < int > own ( rows . begin () + (size_t) t * H , rows . begin () + (size_t) ( t + 1 ) * H ); 955const std::vector < int > row0 ( rows . begin (), rows . begin () + H ); 956gwant [(size_t) t ] = greedy_pen ( lr , own , gp ); 957swant [(size_t) t ] = sampled_reference ( lr , own , sp2 , t ); 958if ( t > 0 && greedy_pen ( lr , row0 , gp ) != gwant [(size_t) t ]) ++ observable ; 959++ rows_checked ; 960} 961char name [ 64 ]; 962std:: snprintf ( name , sizeof name , "per-row history T=%d H=%d greedy" , T , H ); 963bad += run ( name , l , T , gp , gwant , rows_int , H ); 964std:: snprintf ( name , sizeof name , "per-row history T=%d H=%d sampled" , T , H ); 965bad += run ( name , l , T , sp2 , swant , rows_int , H ); 966} 967} 968std:: printf ( " %-34s %s (%d drafted rows pick differently with row 0's history, of %d rows)\n" , 969"per-row histories are observable" , observable > 0 ? "yes" : "*** NO ***" , observable , 970rows_checked ); 971if ( observable == 0 ) ++ bad ; 972} 973 974// ---- fixture 13: HISTORY IDS OUTSIDE THE VOCABULARY ARE IGNORED. The bitmap is sized for n_vocab bits; 975// an id >= n_vocab used to set a bit past its end (a shared-memory write out of bounds - compute-sanitizer 976// memcheck reports it). They can never be a candidate, so the result equals the reference without them. 977{ 978std::mt19937 rng ( 13 ); std::normal_distribution < float > g ( 0.0f , 1.0f ); 979const int H = 16 ; 980std::vector < float > l ((size_t) NV * NT ); 981for (auto & v : l ) v = g ( rng ); 982std::vector < int > hist ((size_t) NT * H , -1 ), valid_only ((size_t) NT * H , -1 ); 983const int junk [] = { NV , NV + 1000 , 0x7fffffff , -5 , 1 << 20 }; 984for (int t = 0 ; t < NT ; ++ t ) { 985for (int j = 0 ; j < H ; ++ j ) { 986const bool bogus = j % 3 == 0 ; 987const int v = bogus ? junk [(size_t) ( j / 3 ) % 5 ] : (int) ( rng () % NV ); 988hist [(size_t) t * H + j ] = v ; 989if (! bogus ) valid_only [(size_t) t * H + j ] = v ; 990} 991l [(size_t) t * NV + hist [(size_t) t * H + 1 ]] = 4.0f ; // a penalised favourite, so penalties matter 992} 993strata::kernels::SamplerParams gp ; 994gp . greedy = true; gp . temperature = 0.0f ; gp . top_k = 0 ; gp . top_p = 1.0f ; 995gp . penalty_last_n = H ; gp . penalty_present = 3.0f ; 996strata::kernels::SamplerParams sp2 = gp ; 997sp2 . greedy = false; sp2 . temperature = 0.8f ; sp2 . top_k = 20 ; sp2 . top_p = 0.95f ; sp2 . seed = 13 ; 998std::vector < int > gwant ((size_t) NT ), swant ((size_t) NT ); 999for (int t = 0 ; t < NT ; ++ t ) { 1000const std::vector < float > lr ( l . begin () + (size_t) t * NV , l . begin () + (size_t) ( t + 1 ) * NV ); 1001const std::vector < int > ok ( valid_only . begin () + (size_t) t * H , valid_only . begin () + (size_t) ( t + 1 ) * H ); 1002{ // the greedy reference with the penalty (reference_pick has none) 1003int best = 0 ; float bv = 0 ; bool first = true; 1004for (int v = 0 ; v < NV ; ++ v ) { 1005int c = 0 ; for (int h : ok ) if ( h == v ) ++ c ; 1006float s = lr [(size_t) v ]; 1007if ( c > 0 ) { if ( s <= 0.0f ) s *= gp . penalty_repeat ; else s /= gp . penalty_repeat ; s -= gp . penalty_present ; } 1008if ( first || s > bv ) { bv = s ; best = v ; first = false; } 1009} 1010gwant [(size_t) t ] = best ; 1011} 1012swant [(size_t) t ] = sampled_reference ( lr , ok , sp2 , t ); 1013} 1014bad += run ( "out-of-vocab history ids (greedy)" , l , NT , gp , gwant , hist , H ); 1015bad += run ( "out-of-vocab history ids (sampled)" , l , NT , sp2 , swant , hist , H ); 1016} 1017 1018// ---- fixture 14: THE top_k CONTRACT. 1..64 as given; 0 ("off") and anything wider use the widest list the 1019// kernel keeps, 64 - and every row is written (the sampled kernel used to print an error for 0 and leave the 1020// row unwritten, which a verify window then read as a token; `run` pre-fills -1 so that fails here). 1021{ 1022std::mt19937 rng ( 14 ); std::normal_distribution < float > g ( 0.0f , 1.0f ); 1023std::vector < float > l ((size_t) NV * NT ); 1024for (auto & v : l ) v = g ( rng ) * 0.3f ; // flat: the 64-wide list matters to the draw 1025strata::kernels::SamplerParams p64 ; 1026p64 . top_k = 64 ; p64 . top_p = 1.0f ; p64 . temperature = 1.5f ; p64 . seed = 14 ; 1027std::vector < int > want ((size_t) NT ); 1028for (int t = 0 ; t < NT ; ++ t ) 1029want [(size_t) t ] = sampled_reference ({ l . begin () + (size_t) t * NV , l . begin () + (size_t) ( t + 1 ) * NV }, 1030{}, p64 , t ); 1031bad += run ( "sampled top_k=64" , l , NT , p64 , want ); 1032strata::kernels::SamplerParams p0 = p64 ; p0 . top_k = 0 ; 1033bad += run ( "sampled top_k=0 means 64" , l , NT , p0 , want ); 1034strata::kernels::SamplerParams p100 = p64 ; p100 . top_k = 100 ; 1035bad += run ( "sampled top_k=100 means 64" , l , NT , p100 , want ); 1036strata::kernels::SamplerParams pneg = p64 ; pneg . top_k = -3 ; 1037bad += run ( "sampled top_k=-3 means 64" , l , NT , pneg , want ); 1038} 1039 1040// ---- fixture 15: `penalty_rows`, host only, against the plain definition: row t = the last h tokens of 1041// tail + window[0..t], -1 padded in front. Covers a tail shorter than, equal to and longer than h, and row 0 1042// equal to the single row the engine staged before 0.1.19. 1043{ 1044int wrong = 0 , cases = 0 ; 1045for (int n_tail : { 0 , 1 , 5 , 63 , 64 , 65 , 300 }) { 1046for (int T : { 1 , 3 , 8 }) { 1047for (int h : { 1 , 4 , 64 , 100 }) { 1048std::vector < int32_t > tail ((size_t) n_tail ), window ((size_t) T ); 1049for (int i = 0 ; i < n_tail ; ++ i ) tail [(size_t) i ] = 1000 + i ; 1050for (int i = 0 ; i < T ; ++ i ) window [(size_t) i ] = 5000 + i ; 1051std::vector < int32_t > rows ((size_t) T * h , 12345 ); 1052strata::kernels:: penalty_rows ( tail . data (), n_tail , window . data (), T , h , rows . data ()); 1053for (int t = 0 ; t < T ; ++ t ) { 1054std::vector < int32_t > seq (tail); 1055seq . insert ( seq . end (), window . begin (), window . begin () + t + 1 ); 1056std::vector < int32_t > expect ((size_t) h , -1 ); 1057const int take = (int) std:: min < size_t > ((size_t) h , seq . size ()); 1058for (int j = 0 ; j < take ; ++ j ) expect [(size_t) ( h - take + j )] = seq [ seq . size () - take + j ]; 1059if (!std:: equal ( expect . begin (), expect . end (), rows . begin () + (size_t) t * h )) ++ wrong ; 1060++ cases ; 1061} 1062// row 0 = the old single-row staging: consumed tail, then the fed-back head last 1063std::vector < int32_t > old ((size_t) h , -1 ); 1064const int take0 = (int) std:: min < int64_t > ( h , (int64_t) n_tail + 1 ); 1065for (int j = 0 ; j < take0 - 1 ; ++ j ) old [(size_t) ( h - take0 + j )] = tail [(size_t) ( n_tail - ( take0 - 1 ) + j )]; 1066old [(size_t) ( h - 1 )] = window [ 0 ]; 1067if (!std:: equal ( old . begin (), old . end (), rows . begin ())) ++ wrong ; 1068++ cases ; 1069} 1070} 1071} 1072std:: printf ( " %-34s %s (%d of %d rows differ)\n" , "penalty_rows layout" , wrong ? "*** WRONG ***" : "matches" , 1073wrong , cases ); 1074bad += wrong ; 1075} 1076 1077// A continuous stream and individual decode calls consume the same draw counters. 1078{ 1079constexpr int count = 32 , vocab = 16 ; 1080std::vector < float > uniform ( count * vocab , 0.0f ); 1081float * input = nullptr ; 1082int * output = nullptr ; 1083check ( cudaMalloc ( & input , uniform . size () * sizeof (float)), "counter logits" ); 1084check ( cudaMalloc ( & output , count * sizeof (int)), "counter output" ); 1085check ( cudaMemcpy ( input , uniform . data (), uniform . size () * sizeof (float), cudaMemcpyHostToDevice ), "counter upload" ); 1086strata::kernels::SamplerParams p ; 1087p . top_k = vocab ; p . top_p = 1.0f ; p . seed = 123 ; p . counter = (uint64_t( 1 ) << 32 ) + 7 ; 1088strata::kernels:: sample_tokens ( input , count , vocab , nullptr , 0 , p , output , nullptr ); 1089std::vector < int > batch (count), singles (count), repeated (count); 1090check ( cudaMemcpy ( batch . data (), output , count * sizeof (int), cudaMemcpyDeviceToHost ), "counter batch" ); 1091for (int i = 0 ; i < count ; ++ i ) { 1092auto one = p ; one . counter += i ; 1093strata::kernels:: sample_tokens ( input , 1 , vocab , nullptr , 0 , one , output + i , nullptr ); 1094} 1095check ( cudaMemcpy ( singles . data (), output , count * sizeof (int), cudaMemcpyDeviceToHost ), "counter singles" ); 1096strata::kernels:: sample_tokens ( input , count , vocab , nullptr , 0 , p , output , nullptr ); 1097check ( cudaMemcpy ( repeated . data (), output , count * sizeof (int), cudaMemcpyDeviceToHost ), "counter repeated" ); 1098bool varies = false; 1099for (int i = 1 ; i < count ; ++ i ) varies |= batch [ i ] != batch [ 0 ]; 1100const bool valid = batch == singles && batch == repeated && varies ; 1101std:: printf ( " sampler draw counter segmentation/repeat: %s\n" , valid ? "PASS" : "FAIL" ); 1102bad += ! valid ; 1103cudaFree ( input ); cudaFree ( output ); 1104} 1105 1106// ---- fixture 16: THE WHOLE top_k LIST, POSITION BY POSITION, UNDER TIES. A pick shows the list 1107// through one draw; this reads the list itself. Every row holds a +inf logit, so the tail's arithmetic is NaN 1108// (inf - inf), no cut fires and no draw lands: the chain returns its LAST kept entry, sel_ids[k - 1]. Launching 1109// top_k = 1..64 then reads the list one position at a time - its set and its order. The rows make the order 1110// rest on the tie rule: hundreds of logits share the top finite values, spread over every split block, warp and 1111// lane; -0 and +0 tie; -inf and NaN are mixed in; a row has fewer finite logits than 64 (the sentinel id 0 must 1112// come out); a penalised row lands its penalised tokens exactly on other tokens' values. Vocabularies: the 1113// engine's 248,320 (a partial last split block), 100,003, 262,144 (the widest split), 262,145 (one more: the 1114// one-block fallback) and 1,000. 1115{ 1116const float inf = std::numeric_limits < float > :: infinity (); 1117const float qnan = std::numeric_limits < float > :: quiet_NaN (); 1118int wrong = 0 , probes = 0 , sentinels = 0 ; 1119for (int nv : { 248320 , 100003 , 262144 , 262145 , 1000 }) { 1120const int T = 4 , H = 64 ; 1121std::mt19937 rng ((unsigned) ( 1600 + nv )); 1122std::normal_distribution < float > g ( 0.0f , 1.0f ); 1123std::vector < float > l ((size_t) nv * T ); 1124for (auto & v : l ) v = std:: floor ( g ( rng ) * 4.0f ) / 4.0f ; // quarter steps: ties everywhere 1125auto spread = [ & ](int j ) { return (int) (((int64_t) j * 7919 + 13 ) % nv ); }; 1126// row 0: 20 logits at 6.25 and 300 at 6.0 over the whole row, two +inf 1127float * r0 = l . data (); 1128for (int j = 0 ; j < 320 ; ++ j ) r0 [ spread ( j )] = j < 20 ? 6.25f : 6.0f ; 1129r0 [ nv / 2 ] = inf ; 1130r0 [ nv - 1 ] = inf ; 1131// row 1: nothing above 0, every zero signed by its id's parity (-0 at even ids), one +inf 1132float * r1 = l . data () + (size_t) nv ; 1133for (int v = 0 ; v < nv ; ++ v ) { 1134r1 [ v ] = - std:: fabs ( r1 [ v ]); 1135if ( r1 [ v ] == 0.0f ) r1 [ v ] = ( v & 1 ) ? 0.0f : -0.0f ; 1136} 1137r1 [ 3 ] = inf ; 1138// row 2: -inf everywhere but ten finite logits (two values), two NaN and a +inf: 11 candidates in all 1139float * r2 = l . data () + (size_t) 2 * nv ; 1140for (int v = 0 ; v < nv ; ++ v ) r2 [ v ] = - inf ; 1141for (int j = 0 ; j < 10 ; ++ j ) r2 [ spread ( j + 400 )] = j < 5 ? 1.0f : 0.5f ; 1142r2 [ spread ( 500 )] = qnan ; 1143r2 [ spread ( 501 )] = qnan ; 1144r2 [ spread ( 502 )] = inf ; 1145// row 3: penalties. Window ids on block and warp edges, repeats, and ids outside the vocabulary; the 1146// penalised tokens sit at 9.0, which repeat 2 / freq 0.25 / present 0.5 turns into 4.0 - 0.25 x count 1147// (3.75, 3.5, ...), values the quarter-step logits share. 1148float * r3 = l . data () + (size_t) 3 * nv ; 1149std::vector < int > hist ((size_t) T * H , -1 ); 1150int * h3 = hist . data () + (size_t) 3 * H ; 1151const int edges [] = { 0 , 1023 , 1024 , 4095 , 4096 , 8191 , 8192 , 12345 , nv / 2 + 1 , nv - 2 }; 1152int hn = 0 ; 1153for (int e : edges ) 1154if ( e < nv && e != nv / 2 ) { 1155h3 [ hn ++ ] = e ; 1156if ( hn % 3 == 0 ) h3 [ hn ++ ] = e ; // counted twice 1157r3 [ e ] = 9.0f ; 1158} 1159h3 [ hn ++ ] = nv ; // ignored: outside 1160h3 [ hn ++ ] = nv + 77 ; 1161h3 [ hn ++ ] = -5 ; 1162for (int j = 0 ; j < 30 ; ++ j ) r3 [ spread ( j + 600 )] = j < 15 ? 3.75f : 3.5f ; 1163r3 [ nv / 2 ] = inf ; // not in the window 1164 1165strata::kernels::SamplerParams base ; 1166base . top_p = 1.0f ; base . min_p = 0.0f ; base . temperature = 0.8f ; base . seed = 16 ; 1167base . penalty_last_n = H ; base . penalty_repeat = 2.0f ; base . penalty_freq = 0.25f ; 1168base . penalty_present = 0.5f ; 1169const int kmax = sampled_k ( 64 , nv ); 1170std::vector < SelList > lists ; 1171for (int t = 0 ; t < T ; ++ t ) 1172lists . push_back ( mirror_select ( l . data () + (size_t) t * nv , nv , window_of ( hist , H , t , H ), base , kmax )); 1173DeviceRows rows (l, T, hist, H); 1174for (int top_k = 0 ; top_k <= 66 ; ++ top_k ) { 1175strata::kernels::SamplerParams p = base ; 1176p . top_k = top_k == 65 ? 100 : top_k == 66 ? -3 : top_k ; // 0, 100 and -3 mean 64 1177p . top_p = ( top_k & 1 ) ? 0.5f : 1.0f ; // both tail branches (NaN: no cut) 1178p . counter = (uint64_t) top_k ; 1179const int k = sampled_k ( p . top_k , nv ); 1180const std::vector < int > got = rows . sample ( p , nullptr ); 1181for (int t = 0 ; t < T ; ++ t ) { 1182const int want = lists [(size_t) t ]. ids [(size_t) ( k - 1 )]; 1183sentinels += ( t == 2 && k > 11 ); 1184++ probes ; 1185if ( got [(size_t) t ] != want ) { 1186if ( wrong < 8 ) 1187std:: printf ( " n_vocab %d row %d top_k %d: position %d want id %d got %d\n" , nv , t , 1188p . top_k , k - 1 , want , got [(size_t) t ]); 1189++ wrong ; 1190} 1191} 1192} 1193} 1194// the fixture must reach the sentinel (row 2 has 11 candidates) or it cannot see the "nothing left" rule 1195std:: printf ( " %-34s %s (%d of %d positions differ; %d sentinel positions)\n" , "top_k list under ties" , 1196wrong || ! sentinels ? "*** WRONG ***" : "matches" , wrong , probes , sentinels ); 1197bad += wrong + ( sentinels == 0 ); 1198} 1199 1200// ---- fixture 17: SAMPLED DRAWS UNDER TIES. The realistic chain - finite logits on half steps, 1201// so dozens of tokens share each value near the top - through every stage: top_k 1 / 20 / 64, top_p 0.9 / 1, 1202// min_p 0 / 0.05, a hot temperature that spreads the draws over the whole list, penalties off and on (half of 1203// each window on the row's head, so they reorder it). 17 rows (the split's scratch is first sized for 16: this 1204// regrows it), on the legacy stream and on a created one. Observability: some picks must be tokens that tie 1205// with another kept token, or the tie rule would go untested. 1206{ 1207const int T = 17 , H = 64 ; 1208cudaStream_t cs = nullptr ; 1209check ( cudaStreamCreate ( & cs ), "fixture 17 stream" ); 1210int wrong = 0 , draws = 0 , tied = 0 ; 1211for (int nv : { 248320 , 512 }) { 1212std::mt19937 rng ((unsigned) ( 1700 + nv )); 1213std::normal_distribution < float > g ( 0.0f , 1.5f ); 1214std::vector < float > l ((size_t) nv * T ); 1215for (auto & v : l ) v = std:: floor ( g ( rng ) * 2.0f ) / 2.0f ; 1216if ( nv == 512 ) 1217for (auto & v : l ) v = std:: floor ( v / 2.0f ); // whole steps: a few big tie groups 1218std::vector < int > hist ((size_t) T * H ); 1219for (int t = 0 ; t < T ; ++ t ) { 1220const float * row = l . data () + (size_t) t * nv ; 1221const float mx = * std:: max_element ( row , row + nv ); 1222std::vector < int > head ; 1223for (int v = 0 ; v < nv ; ++ v ) 1224if ( row [ v ] >= mx - 1.0f ) head . push_back ( v ); 1225for (int j = 0 ; j < H ; ++ j ) 1226hist [(size_t) t * H + j ] = ( j & 1 ) ? (int) ( rng () % (unsigned) nv ) 1227: head [(size_t) ( rng () % (unsigned) head . size ())]; 1228} 1229DeviceRows rows (l, T, hist, H); 1230int config = 0 ; 1231for (int pen = 0 ; pen < 2 ; ++ pen ) { 1232strata::kernels::SamplerParams base ; 1233base . temperature = 2.5f ; base . seed = 17 ; 1234base . penalty_last_n = pen ? H : 0 ; 1235base . penalty_repeat = 1.25f ; base . penalty_freq = 0.25f ; base . penalty_present = 0.5f ; 1236const int kmax = sampled_k ( 64 , nv ); 1237std::vector < SelList > lists ; 1238for (int t = 0 ; t < T ; ++ t ) 1239lists . push_back ( mirror_select ( l . data () + (size_t) t * nv , nv , window_of ( hist , H , t , base . penalty_last_n ), 1240base , kmax )); 1241for (int top_k : { 1 , 20 , 64 }) 1242for (float top_p : { 0.9f , 1.0f }) 1243for (float min_p : { 0.0f , 0.05f }) 1244for (cudaStream_t st : {(cudaStream_t) nullptr , cs }) { 1245strata::kernels::SamplerParams p = base ; 1246p . top_k = top_k ; p . top_p = top_p ; p . min_p = min_p ; 1247p . counter = (uint64_t) ( 1000 * ++ config ); 1248const int k = sampled_k ( top_k , nv ); 1249const std::vector < int > got = rows . sample ( p , st ); 1250for (int t = 0 ; t < T ; ++ t ) { 1251const SelList & sl = lists [(size_t) t ]; 1252const int want = mirror_pick ( sl , k , p , t ); 1253++ draws ; 1254int same = 0 ; 1255for (int i = 0 ; i < k ; ++ i ) { 1256if ( sl . ids [(size_t) i ] != want ) continue ; 1257for (int j = 0 ; j < k ; ++ j ) same += sl . logit [(size_t) j ] == sl . logit [(size_t) i ]; 1258break ; 1259} 1260tied += same > 1 ; 1261if ( got [(size_t) t ] != want ) { 1262if ( wrong < 8 ) 1263std:: printf ( " n_vocab %d row %d top_k %d top_p %.2f min_p %.2f pen %d: " 1264"want %d got %d\n" , nv , t , top_k , (double) top_p , 1265(double) min_p , pen , want , got [(size_t) t ]); 1266++ wrong ; 1267} 1268} 1269} 1270} 1271} 1272cudaStreamDestroy ( cs ); 1273std:: printf ( " %-34s %s (%d of %d draws differ; %d picks tie with another kept token)\n" , 1274"sampled draws under ties" , wrong || ! tied ? "*** WRONG ***" : "matches" , wrong , draws , tied ); 1275bad += wrong + ( tied == 0 ); 1276} 1277 1278// ---- fixture 18: THE DEFAULT PATH'S AUTOMATIC FALLBACKS. (a) A stream under graph capture 1279// (ThreadLocal mode) gets the one-block kernel, penalty bitmap in dynamic shared memory, inside the graph: the 1280// capture must succeed and the replayed graph (twice) must pick the mirror's tokens; the same stream uncaptured 1281// then takes the split path (its scratch is first allocated after the capture) and picks the same. (b) More 1282// rows than a split launch takes (64) fall back to one block; exactly 64 stay split. 1283{ 1284int wrong = 0 , draws = 0 ; 1285const int H = 64 ; 1286auto compare = [ & ]( const char * what , const std::vector < int >& got , const std::vector < SelList >& lists , int k , 1287const strata::kernels::SamplerParams & p ) { 1288for (size_t t = 0 ; t < got . size (); ++ t ) { 1289const int want = mirror_pick ( lists [ t ], k , p , (int) t ); 1290++ draws ; 1291if ( got [ t ] != want ) { 1292if ( wrong < 8 ) std:: printf ( " %s row %zu: want %d got %d\n" , what , t , want , got [ t ]); 1293++ wrong ; 1294} 1295} 1296}; 1297auto make = [ & ](int nv , int T , unsigned seed , std::vector < float >& l , std::vector < int >& hist ) { 1298std::mt19937 rng (seed); 1299std::normal_distribution < float > g ( 0.0f , 1.5f ); 1300l . assign ((size_t) nv * T , 0.0f ); 1301for (auto & v : l ) v = std:: floor ( g ( rng ) * 2.0f ) / 2.0f ; 1302hist . assign ((size_t) T * H , 0 ); 1303for (auto & h : hist ) h = (int) ( rng () % (unsigned) nv ); 1304}; 1305{ 1306const int nv = 248320 , T = 3 ; 1307std::vector < float > l ; 1308std::vector < int > hist ; 1309make ( nv , T , 1800u , l , hist ); 1310strata::kernels::SamplerParams p ; 1311p . top_k = 20 ; p . top_p = 0.9f ; p . temperature = 2.5f ; p . seed = 18 ; p . counter = 77 ; 1312p . penalty_last_n = H ; p . penalty_repeat = 1.25f ; p . penalty_freq = 0.25f ; p . penalty_present = 0.5f ; 1313const int k = sampled_k ( p . top_k , nv ); 1314std::vector < SelList > lists ; 1315for (int t = 0 ; t < T ; ++ t ) 1316lists . push_back ( mirror_select ( l . data () + (size_t) t * nv , nv , window_of ( hist , H , t , H ), p , k )); 1317DeviceRows rows (l, T, hist, H); 1318cudaStream_t cs = nullptr ; 1319check ( cudaStreamCreate ( & cs ), "fixture 18 stream" ); 1320check ( cudaMemset ( rows . o , 0xFF , (size_t) T * sizeof (int)), "fixture 18 fill" ); 1321cudaGraph_t graph = nullptr ; 1322cudaGraphExec_t exec = nullptr ; 1323check ( cudaStreamBeginCapture ( cs , cudaStreamCaptureModeThreadLocal ), "begin capture" ); 1324strata::kernels:: sample_tokens ( rows . l , T , nv , rows . h , H , p , rows . o , cs ); 1325check ( cudaStreamEndCapture ( cs , & graph ), "end capture" ); 1326check ( cudaGraphInstantiate ( & exec , graph , 0 ), "instantiate" ); 1327for (int replay = 0 ; replay < 2 ; ++ replay ) { 1328check ( cudaMemset ( rows . o , 0xFF , (size_t) T * sizeof (int)), "fixture 18 refill" ); 1329check ( cudaGraphLaunch ( exec , cs ), "graph launch" ); 1330check ( cudaStreamSynchronize ( cs ), "graph sync" ); 1331std::vector < int > got ((size_t) T ); 1332check ( cudaMemcpy ( got . data (), rows . o , got . size () * sizeof (int), cudaMemcpyDeviceToHost ), "back" ); 1333compare ( "captured graph" , got , lists , k , p ); 1334} 1335cudaGraphExecDestroy ( exec ); 1336cudaGraphDestroy ( graph ); 1337compare ( "same stream, uncaptured" , rows . sample ( p , cs ), lists , k , p ); 1338cudaStreamDestroy ( cs ); 1339} 1340for (int T : { 64 , 70 }) { 1341const int nv = 512 ; 1342std::vector < float > l ; 1343std::vector < int > hist ; 1344make ( nv , T , 1810u + (unsigned) T , l , hist ); 1345strata::kernels::SamplerParams p ; 1346p . top_k = 64 ; p . top_p = 1.0f ; p . temperature = 2.5f ; p . seed = 18 ; p . counter = (uint64_t) T ; 1347const int k = sampled_k ( p . top_k , nv ); 1348std::vector < SelList > lists ; 1349for (int t = 0 ; t < T ; ++ t ) lists . push_back ( mirror_select ( l . data () + (size_t) t * nv , nv , {}, p , k )); 1350DeviceRows rows ( l , T , hist , 0 ); 1351compare ( T > 64 ? "70 rows (one block)" : "64 rows (split)" , rows . sample ( p , nullptr ), lists , k , p ); 1352} 1353std:: printf ( " %-34s %s (%d of %d draws differ)\n" , "fallbacks: graph capture, row cap" , 1354wrong ? "*** WRONG ***" : "matches" , wrong , draws ); 1355bad += wrong ; 1356} 1357 1358// ---- GUMBEL-MAX (STRATA_SPEC_GUMBEL, p.gumbel). (a) The kernel's pick equals the host reference's, draw for draw, 1359// under the chains the server uses (top_k / top_p / min_p / temperature). (b) It is an exact sample: over many 1360// counters the picks' frequencies match the softmax of the surviving logits. (c) It is a different stream from 1361// the inverse-CDF draw (the flag is really read), and greedy rows ignore it. 1362{ 1363int wrong = 0 , draws = 0 ; 1364const int nv = 512 , T = 16 ; 1365std::vector < float > l ((size_t) nv * T ); 1366std::vector < int > hist ; 1367{ 1368std::mt19937 rng ( 4242u ); 1369std::normal_distribution < float > gd ( 0.0f , 2.0f ); 1370for (auto & v : l ) v = gd ( rng ); 1371} 1372struct Chain { int top_k ; float top_p , min_p , temp ; }; 1373for ( const Chain c : {Chain{ 20 , 0.95f , 0.0f , 1.0f }, Chain{ 0 , 1.0f , 0.0f , 0.7f }, Chain{ 40 , 0.9f , 0.05f , 1.3f }}) { 1374strata::kernels::SamplerParams p ; 1375p . top_k = c . top_k ; p . top_p = c . top_p ; p . min_p = c . min_p ; p . temperature = c . temp ; 1376p . seed = 77 ; p . counter = 1000 ; p . gumbel = true; 1377std::vector < int > want ((size_t) T ); 1378for (int t = 0 ; t < T ; ++ t ) 1379want [(size_t) t ] = sampled_reference ({ l . begin () + (size_t) t * nv , l . begin () + (size_t) ( t + 1 ) * nv }, {}, p , t ); 1380DeviceRows rows ( l , T , hist , 0 ); 1381const std::vector < int > got = rows . sample ( p , nullptr ); 1382for (int t = 0 ; t < T ; ++ t ) wrong += got [(size_t) t ] != want [(size_t) t ]; 1383draws += T ; 1384} 1385std:: printf ( " %-34s %s (%d of %d draws differ)\n" , "gumbel: kernel vs reference" , wrong ? "*** WRONG ***" : "matches" , 1386wrong , draws ); 1387bad += wrong ; 1388 1389// (b) frequencies: one 12-logit row, every row of a launch the same logits at its own counter 1390const int nv2 = 12 , R = 64 , launches = 160 ; // 10,240 draws 1391std::vector < float > row = { 2.0f , 1.5f , 1.2f , 1.0f , 0.5f , 0.3f , 0.0f , -0.5f , -1.0f , -1.5f , -2.0f , -3.0f }; 1392std::vector < float > lr ; 1393for (int r = 0 ; r < R ; ++ r ) lr . insert ( lr . end (), row . begin (), row . end ()); 1394strata::kernels::SamplerParams g ; 1395g . top_k = 0 ; g . top_p = 1.0f ; g . temperature = 1.0f ; g . seed = 5 ; g . gumbel = true; 1396std::vector < double > freq ((size_t) nv2 , 0.0 ); 1397DeviceRows rr ( lr , R , {}, 0 ); 1398for (int k2 = 0 ; k2 < launches ; ++ k2 ) { 1399g . counter = (uint64_t) k2 * R ; 1400for (int id : rr . sample ( g , nullptr )) freq [(size_t) id ] += 1.0 ; 1401} 1402double z = 0.0 , tv = 0.0 ; 1403for (float v : row ) z += std:: exp ((double) v ); 1404for (int i = 0 ; i < nv2 ; ++ i ) tv += std:: fabs ( freq [(size_t) i ] / ( R * launches ) - std:: exp ((double) row [(size_t) i ]) / z ); 1405tv *= 0.5 ; 1406const bool freq_bad = tv > 0.02 ; // 10,240 draws: total variation ~0.01 by chance 1407std:: printf ( " %-34s %s (total variation %.4f over %d draws)\n" , "gumbel: frequencies = softmax" , 1408freq_bad ? "*** WRONG ***" : "matches" , tv , R * launches ); 1409bad += freq_bad ; 1410 1411// (c) the flag is read (a different stream than the inverse-CDF draw), and greedy ignores it 1412strata::kernels::SamplerParams a ; a . top_k = 20 ; a . top_p = 0.95f ; a . temperature = 1.0f ; a . seed = 9 ; a . counter = 3 ; 1413strata::kernels::SamplerParams b = a ; b . gumbel = true; 1414DeviceRows rows ( l , T , hist , 0 ); 1415const std::vector < int > ga = rows . sample ( a , nullptr ), gb = rows . sample ( b , nullptr ); 1416int same = 0 ; 1417for (int t = 0 ; t < T ; ++ t ) same += ga [(size_t) t ] == gb [(size_t) t ]; 1418strata::kernels::SamplerParams ga2 ; ga2 . greedy = true; ga2 . temperature = 0.0f ; 1419strata::kernels::SamplerParams gb2 = ga2 ; gb2 . gumbel = true; 1420const bool greedy_same = rows . sample ( ga2 , nullptr ) == rows . sample ( gb2 , nullptr ); 1421const bool flag_bad = same == T || ! greedy_same ; 1422std:: printf ( " %-34s %s (%d of %d sampled picks equal the inverse-CDF ones; greedy %s)\n" , "gumbel: flag read, greedy unchanged" , 1423flag_bad ? "*** WRONG ***" : "matches" , same , T , greedy_same ? "unchanged" : "CHANGED" ); 1424bad += flag_bad ; 1425} 1426 1427std:: printf ( "\nsampler: %d failures\n" , bad ); 1428if ( bad ) return 1 ; 1429if ( selftest ) std:: printf ( "sampler_parity OK\n" ); 1430return 0 ; 1431}