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