okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
5af104b51
main
1// src/kernels/qsa_parity.cpp - P2.S2's test for the QSA cache, indexer, selection and attention. 2// 3// `ref/qsa.py` carries eleven PROPERTY checks and `ref/model.py::_qsa` is the layer as the model runs it. The 4// readings a prose transcription gets WRONG, each of which produces a well-formed result of the right shape, 5// are computed here the wrong way round AND required to differ MATERIALLY before the kernel is judged against 6// the right one - a test that only does the second half passes against either reading: 7// 8// 1. `pooled[b]` is rotated at the block's FIRST cell. The reference's PROPERTY 4 pins it against the 9// block's LAST cell; both give a unit-norm vector and the same downstream shape. 10// 2. Pool THEN norm (`rms_norm(mean(x))`) and not norm THEN pool (`mean(rms_norm(x))`). `ref/model.py` L358 11// is explicit, and the two differ whenever the four cells have different magnitudes. 12// 3. The spare slot's key is `rms_norm(raw[0])` - cell ZERO - and not the last raw key, and the tail cells 13// map to THAT slot and not to the last complete block. A three-row raw tail cannot produce it unless 14// cell 0's key is kept, which is what makes this a real design constraint rather than a detail. 15// 4. The indexer's Relu is PER HEAD, summed afterwards. `relu(sum_h dot_h)` is the rival reading and 16// differs whenever any head's dot is negative. 17// 5. The q -> kv head map is `q / 12` (integer division), NOT `q % 2`. `ref/qsa.py` PROPERTY 7 tests the 18// same thing; with 24 and 2 the two give [0 x12, 1 x12] and [0,1,0,1,...]. 19// 6. The attention reads ONLY the selected cells. The source writes -inf into the mask and zeros at the 20// top-k indices, so an unselected cell has weight exactly zero even when it would score highest - 21// PROPERTY 8's fixture, reproduced here with its own numbers. 22// 7. `attn *= sigmoid(gate)` with the gate taken from the SECOND half of each head's 2*head_dim block, and 23// the rounding to fp16 happening AFTER the multiply (one rounding, not two). 24// 8. The KV cache is PAGED and the page table is not assumed to be the identity: the pool is written and 25// read back at page_size 1, 4 and 512 with a REVERSED table, and the kernel's own reading of the layout 26// is compared against two rivals (linear, i.e. the table ignored; and cell-major inside the page). 27// 28// THE METRIC. Both sums here - the indexer's sum of four relu'd dots and the attention's weighted sum of 29// value rows - cancel, so a plain |want-got|/|want| reports the condition number instead of the arithmetic. 30// The project has made that mistake four times (rounds 169, 189, 194, 196); where a sum is compared below, the 31// denominator is the magnitude of the TERMS. 32// 33// WHAT SETS EACH TOLERANCE, because a tolerance nobody can explain is one nobody can tighten: 34// * the fp16 converter, the pool contents, the gathered scratch and the spare indexer key: EXACT. The only 35// arithmetic is a conversion, and section 0 checks that conversion against numpy's float16 over 395 36// vectors covering ties in both directions, subnormals and overflow - an oracle sharing no code with it - 37// plus all 65,536 fp16 patterns in the reverse direction. 38// * the pooled block keys: 1e-6. The pooling and the norm are double on both sides and are bit-exact 39// BEFORE the rotation; the residual is `rope_neox_apply` (f32, reused rather than re-implemented) against 40// the reference's float64 rotation, the class round 189 measured at ~1e-7. 41// * the indexer scores: 1e-6 against Sum|dot_h| + |bias|, set by the fp32 storage of the pooled keys - 42// 2^-24 per element over a 128-term dot. 43// * the selected ids: EXACT. `docs/capture-format.md` L127 gives `indexer_ids` no tolerance. 44// * the attention against a reference reading the SAME fp16 cache: 1e-5, set by f32 accumulation over 45// 256-term dots plus `expf`'s 2 ulp. This is the KERNEL's number. 46// * the attention against a reference reading the f32 keys: REPORTED and then checked against the phase's 47// 1e-3 for FP16 paths. That difference is the FP16 CACHE's cost, not the kernel's, and it is kept 48// separate so a kernel bug cannot hide inside it. 49#define DPCT_PROFILING_ENABLED 50#include <sycl/sycl.hpp> 51#include <dpct/dpct.hpp> 52#include "strata/kernels/qsa.hpp" 53#include "strata/kernels/native_qsa_indexer.hpp" 54 55#include "strata/kernels/f16_bits.hpp" 56#include "strata/kernels/rope.hpp" 57 58#include <algorithm> 59#include <cmath> 60#include <cstdio> 61#include <cstdlib> 62#include <cstring> 63#include <functional> 64#include <random> 65#include <string> 66#include <vector> 67 68namespace { 69 70using strata::kernels::f16_from_f32 ; 71using strata::kernels::f32_from_f16 ; 72 73void check (dpct::err0 e ,const char * what ) { 74} 75 76/// A device buffer with the boilerplate folded in. A test that allocates twenty buffers by hand spends its 77/// attention on memcpy arguments instead of on the kernel. 78template < typename T > 79struct Dev { 80T * p = nullptr ; 81Dev ()= default ; 82explicit Dev (size_t n ) {alloc (n ); } 83 ~Dev () {if (p ) sycl::free (p , dpct::get_in_order_queue ()); } 84Dev (const Dev & )= delete ; 85Dev & operator= (const Dev & )= delete ; 86void alloc (size_t n ) { 87if (p ) { sycl::free (p , dpct::get_in_order_queue ());p = nullptr ; } 88if (n )check ( 89DPCT_CHECK_ERROR (p = (T * )sycl::malloc_device ( 90n * sizeof (T ), dpct::get_in_order_queue ())), 91"cudaMalloc" ); 92 } 93void put (const std::vector < T >& v ) { 94if (!p )alloc (v .size ()); 95/* 96DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, 97assuming in the original code the source host memory is pageable memory. 98If the memory is not pageable, call wait() on event return by memcpy API 99to ensure synchronization behavior. 100*/ 101check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy ( 102p ,v .data (),v .size ()* sizeof (T )).wait ()), 103"H2D" ); 104 } 105 std::vector < T > get (size_t n )const { 106 std::vector < T > v (n ); 107check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()) 108 .memcpy (v .data (),p ,n * sizeof (T )) 109 .wait ()), 110"D2H" ); 111return v ; 112 } 113}; 114 115std::vector < double > as_d (const std::vector < float >& v ) {return std::vector < double > (v .begin (),v .end ()); } 116std::vector < float > as_f (const std::vector < double >& v ) { 117 std::vector < float > o (v .size ()); 118for (size_t i = 0 ;i < v .size ();++ i )o [i ]= (float )v [i ]; 119return o ; 120} 121 122/// Relative error against the magnitude of the TERMS. See the header comment. 123double rel_terms (double want ,double got ,double terms ) { 124return std::fabs (want - got ) / (terms > 1e-30 ?terms :1e-30 ); 125} 126 127double rel_l1 (const std::vector < double >& a ,const std::vector < double >& b ) { 128double d = 0 ,m = 0 ; 129for (size_t i = 0 ;i < a .size ();++ i ) { 130d += std::fabs (a [i ]- b [i ]); 131m += std::fabs (a [i ]); 132 } 133return d / (m > 1e-30 ?m :1e-30 ); 134} 135 136int g_bad = 0 ; 137std::string pct (double rel ) { 138char b [32 ]; 139 std::snprintf (b ,sizeof b ,"%.2f%% apart" ,rel * 100.0 ); 140return b ; 141} 142void verdict (const std::string & name ,bool ok ,const std::string & detail = "" ) { 143 std::printf (" %-48s %-6s %s\n" ,name .c_str (),ok ?"yes" :"*** NO ***" ,detail .c_str ()); 144if (!ok )++ g_bad ; 145} 146void report (const std::string & name ,double v ,const char * unit ) { 147 std::printf (" %-48s %s %.3e\n" ,name .c_str (),unit ,v ); 148} 149void require (const std::string & name ,bool ok ,const std::string & detail = "" ) { 150 std::printf (" %-48s %-6s %s\n" ,name .c_str (),ok ?"ok" :"*** BAD ***" ,detail .c_str ()); 151if (!ok )++ g_bad ; 152} 153 154// ================= the reference: ref/qsa.py + ref/model.py, in double ================= 155 156/// Which of the rival readings to compute. The defaults are the SOURCE's reading. 157struct Alt { 158bool rotate_at_block_start = true;///< false: rotate at the block's LAST cell (WRONG) 159bool pool_then_norm = true;///< false: mean of the per-cell norms (WRONG) 160bool dead_from_first = true;///< false: the spare key from the LAST raw key (WRONG) 161bool rope_raw = false;///< true: rotate the raw keys before pooling (WRONG) 162bool relu_per_head = true;///< false: relu(sum of the head dots) (WRONG) 163bool use_relu = true;///< false: no relu at all (WRONG) 164bool use_bias = true;///< false: drop the per-block bias (WRONG) 165bool kv_divide = true;///< false: q % n_head_kv instead of q / 12 (WRONG) 166bool apply_scale = true;///< false: no 1/sqrt(head_dim) (WRONG) 167bool gate_second_half = true;///< false: the gate from the FIRST half (WRONG) 168bool gate_sigmoid = true;///< false: silu instead of sigmoid (WRONG) 169}; 170 171/// `x*y + z` with the product ROUNDED first, i.e. no FMA contraction. 172/// 173/// MSVC contracts `ss += v*v` into an FMA even under /fp:precise, so the reference was MORE accurate than 174/// the kernel's explicit `__fadd_rn(__fmul_rn(v, v))` and the spare key came out one bit different in 7 of 175/// 128 components. The kernel's arithmetic is what is under test, so the reference REPRODUCES it instead of 176/// beating it; `volatile` is what stops the compiler re-fusing the two operations. 177double mul_add_plain (double x ,double y ,double z ) { 178const volatile double p = x * y ; 179return z + p ; 180} 181 182/// `ref/qsa.py::rms_norm` in double, in place. `w` may be empty (w = None). 183void ref_rms_norm (std::vector < double >& x ,const std::vector < float >& w ,float eps ) { 184double ss = 0 ; 185for (double v :x )ss = mul_add_plain (v ,v ,ss ); 186const double inv = 1.0 / std::sqrt (ss / (double )x .size ()+ (double )eps ); 187for (size_t i = 0 ;i < x .size ();++ i )x [i ]= x [i ]* inv * (w .empty () ?1.0 : (double )w [i ]); 188} 189 190/// `ref/qsa.py::rope_neox` in double: NEOX pairs (i, i + n_rot/2), partial over the first n_rot dims. 191/// 192/// `terms`, when given, receives the magnitude of each component's TERMS - `|a c| + |b s|` where the 193/// rotation subtracts - so a comparison can divide by that instead of by the result, which cancels. 194void ref_rope_neox (std::vector < double >& x ,double pos ,int n_rot ,double theta , 195 std::vector < double >* terms = nullptr ) { 196const int half = n_rot /2 ; 197 std::vector < double > a (x .begin (),x .begin ()+ half ),b (x .begin ()+ half ,x .begin ()+ n_rot ); 198if (terms ) { 199terms -> assign (x .size (),0.0 ); 200for (size_t i = (size_t )n_rot ;i < x .size ();++ i ) (* terms )[i ]= std::fabs (x [i ]); 201 } 202for (int i = 0 ;i < half ;++ i ) { 203const double inv = std::pow (theta ,-2.0 * (double )i / (double )n_rot ); 204const double ang = pos * inv ,c = std::cos (ang ),s = std::sin (ang ); 205x [i ]= a [i ]* c - b [i ]* s ; 206x [half + i ]= a [i ]* s + b [i ]* c ; 207if (terms ) { 208 (* terms )[i ]= std::fabs (a [i ]* c )+ std::fabs (b [i ]* s ); 209 (* terms )[half + i ]= std::fabs (a [i ]* s )+ std::fabs (b [i ]* c ); 210 } 211 } 212} 213 214const int64_t REF_R = 4 ;///< IDX_BLOCK, checked against the shapes at the top of main 215 216/// `QsaCache`, holding f64 rows - the reference never sees an fp16 key. 217struct RefCache { 218 std::vector < std::vector < double >> k ,v ,raw ; 219 std::vector < double > pos ; 220int64_t size ()const {return (int64_t )pos .size (); } 221void append (std::vector < double > kk , std::vector < double > vv , std::vector < double > rr ,double p ) { 222k .push_back (std::move (kk )); 223v .push_back (std::move (vv )); 224raw .push_back (std::move (rr )); 225pos .push_back (p ); 226 } 227}; 228 229/// `QsaCache.pooled_raw(r)` - BEFORE the norm, which is the only place the 1/r divisor is observable. 230std::vector < double > ref_pooled_raw (const RefCache & c ) { 231const int64_t n_bid = c .size () /REF_R ,dim = (int64_t )c .raw [0 ].size (); 232 std::vector < double > out ((size_t )n_bid * dim ,0.0 ); 233for (int64_t b = 0 ;b < n_bid ;++ b ) 234for (int64_t i = 0 ;i < REF_R ;++ i ) 235for (int64_t d = 0 ;d < dim ;++ d )out [(size_t )b * dim + d ]+= c .raw [(size_t ) (b * REF_R + i )][(size_t )d ]; 236for (auto & x :out )x /= (double )REF_R ; 237return out ; 238} 239 240/// `pooled_keys` + `dead_pooled_key`, in the readback order `indexer_scores` uses: (n_bid + 1, idx_dim). 241std::vector < double > ref_pooled (const RefCache & c ,const std::vector < float >& w_kn ,float eps ,int n_rot , 242double theta ,const Alt & o , 243 std::vector < double >* terms_out = nullptr ) { 244const int64_t n_bid = c .size () /REF_R ,dim = (int64_t )c .raw [0 ].size (); 245 std::vector < double > pooled ((size_t ) (n_bid + 1 )* dim ,0.0 ); 246 std::vector < std::vector < double >> rows (c .raw ); 247if (o .rope_raw ) 248for (size_t j = 0 ;j < rows .size ();++ j )ref_rope_neox (rows [j ],c .pos [j ],n_rot ,theta ); 249 250for (int64_t b = 0 ;b < n_bid ;++ b ) { 251 std::vector < double > m ((size_t )dim ,0.0 ); 252if (o .pool_then_norm ) { 253for (int64_t i = 0 ;i < REF_R ;++ i ) 254for (int64_t d = 0 ;d < dim ;++ d ) 255m [(size_t )d ]+= rows [(size_t ) (b * REF_R + i )][(size_t )d ] / (double )REF_R ; 256ref_rms_norm (m ,w_kn ,eps ); 257 }else { 258for (int64_t i = 0 ;i < REF_R ;++ i ) { 259 std::vector < double > one = rows [(size_t ) (b * REF_R + i )]; 260ref_rms_norm (one ,w_kn ,eps ); 261for (int64_t d = 0 ;d < dim ;++ d )m [(size_t )d ]+= one [(size_t )d ] / (double )REF_R ; 262 } 263 } 264 std::vector < double > terms ; 265ref_rope_neox (m ,o .rotate_at_block_start ?c .pos [(size_t ) (b * REF_R )] 266 :c .pos [(size_t ) (b * REF_R + REF_R - 1 )], 267n_rot ,theta ,terms_out ?& terms :nullptr ); 268for (int64_t d = 0 ;d < dim ;++ d )pooled [(size_t )b * dim + d ]= m [(size_t )d ]; 269if (terms_out ) { 270if (b == 0 )terms_out -> assign ((size_t ) (n_bid + 1 )* dim ,0.0 ); 271for (int64_t d = 0 ;d < dim ;++ d ) (* terms_out )[(size_t )b * dim + d ]= terms [(size_t )d ]; 272 } 273 } 274 std::vector < double > dead = rows [o .dead_from_first ?0 :rows .size ()- 1 ]; 275ref_rms_norm (dead ,w_kn ,eps ); 276ref_rope_neox (dead ,0.0 ,n_rot ,theta );// the identity, but computed the reference's way 277for (int64_t d = 0 ;d < dim ;++ d )pooled [(size_t )n_bid * dim + d ]= dead [(size_t )d ]; 278return pooled ; 279} 280 281/// `ref/qsa.py::indexer_scores` - per CELL, after the `cell_block` mapping. 282std::vector < double > ref_indexer_scores (const std::vector < double >& pooled ,int64_t n_bid , 283const std::vector < double >& q_idx ,int64_t idx_n_head ,int64_t idx_dim , 284const std::vector < float >& bias ,int64_t n_kv ,const Alt & o ) { 285 std::vector < double > per_block ((size_t )n_bid + 1 ,0.0 ); 286for (int64_t b = 0 ;b <=n_bid ;++ b ) { 287double s = 0 ; 288for (int64_t h = 0 ;h < idx_n_head ;++ h ) { 289double dot = 0 ; 290for (int64_t d = 0 ;d < idx_dim ;++ d ) 291dot += pooled [(size_t )b * idx_dim + d ]* q_idx [(size_t )h * idx_dim + d ]; 292if (!o .use_relu )s += dot ; 293else if (o .relu_per_head )s += dot > 0 ?dot :0.0 ; 294else s += dot ; 295 } 296if (o .use_relu && !o .relu_per_head )s = s > 0 ?s :0.0 ; 297if (o .use_bias && !bias .empty ())s += (double )bias [(size_t )b ]; 298if (b == n_bid && n_kv %REF_R != 0 )s = (float )s + 1e9f ; 299per_block [(size_t )b ]= s ; 300 } 301 std::vector < double > cell ((size_t )n_kv ,0.0 ); 302for (int64_t j = 0 ;j < n_kv ;++ j )cell [(size_t )j ]= per_block [(size_t ) (j /REF_R < n_bid ?j /REF_R :n_bid )]; 303return cell ; 304} 305 306/// `ref/qsa.py::select_cells`, spelled with a stable sort rather than the kernel's threshold search, so the 307/// two are independent implementations of one rule: score DESCENDING, ties by ASCENDING index. 308std::vector < int32_t > ref_select (const std::vector < double >& scores ,int64_t n_kv ,int64_t top_k ,bool dense ) { 309 std::vector < int32_t > idx ((size_t )n_kv ); 310for (int64_t j = 0 ;j < n_kv ;++ j )idx [(size_t )j ]= (int32_t )j ; 311if (dense )return idx ; 312const int64_t width = std::min < int64_t > (n_kv ,top_k + REF_R - 1 ); 313 std::stable_sort (idx .begin (),idx .end (), [& ](int32_t a ,int32_t b ) { 314const double sa = scores [(size_t )a ],sb = scores [(size_t )b ]; 315if (sa != sb )return sa > sb ; 316return a < b ; 317 }); 318idx .resize ((size_t )width ); 319 std::sort (idx .begin (),idx .end ()); 320return idx ; 321} 322 323/// `ref/qsa.py::qsa_attend` over an EXPLICIT selected set, reading K/V from whichever table the caller passes 324/// so that one piece of code runs on the f64 keys and on the fp16 cache's exact f32 values. 325std::vector < double > ref_attend (const std::vector < double >& q ,int64_t n_head ,int64_t n_head_kv ,int64_t head_dim , 326const std::vector < int32_t >& ids ,const std::vector < std::vector < double >>& k , 327const std::vector < std::vector < double >>& v ,const Alt & o , 328 std::vector < double >* weights_out ) { 329const double scale = o .apply_scale ?1.0 / std::sqrt ((double )head_dim ) :1.0 ; 330 std::vector < double > out ((size_t )n_head * head_dim ,0.0 ); 331if (weights_out )weights_out -> assign ((size_t )n_head * ids .size (),0.0 ); 332for (int64_t h = 0 ;h < n_head ;++ h ) { 333const int64_t kv = o .kv_divide ?h / (n_head /n_head_kv ) :h %n_head_kv ; 334 std::vector < double > sc (ids .size ()); 335for (size_t j = 0 ;j < ids .size ();++ j ) { 336double dot = 0 ; 337for (int64_t d = 0 ;d < head_dim ;++ d ) 338dot += k [(size_t )ids [j ]][(size_t ) (kv * head_dim + d )]* q [(size_t ) (h * head_dim + d )]; 339sc [j ]= dot * scale ; 340 } 341const double mx = * std::max_element (sc .begin (),sc .end ()); 342double sum = 0 ; 343for (auto & s :sc ) {s = std::exp (s - mx );sum += s ; } 344for (auto & s :sc )s /=sum ; 345if (weights_out ) 346for (size_t j = 0 ;j < ids .size ();++ j ) (* weights_out )[(size_t )h * ids .size ()+ j ]= sc [j ]; 347for (int64_t d = 0 ;d < head_dim ;++ d ) { 348double acc = 0 ; 349for (size_t j = 0 ;j < ids .size ();++ j )acc += sc [j ]* v [(size_t )ids [j ]][(size_t ) (kv * head_dim + d )]; 350out [(size_t ) (h * head_dim + d )]= acc ; 351 } 352 } 353return out ; 354} 355 356/// `ref/model.py::_qsa`'s last two lines. 357std::vector < double > ref_gate (const std::vector < double >& attn ,const std::vector < double >& q_full ,int64_t n_head , 358int64_t head_dim ,const Alt & o ) { 359 std::vector < double > out ((size_t )n_head * head_dim ,0.0 ); 360for (int64_t h = 0 ;h < n_head ;++ h ) 361for (int64_t d = 0 ;d < head_dim ;++ d ) { 362const int64_t gi = o .gate_second_half ?h * 2 * head_dim + head_dim + d :h * 2 * head_dim + d ; 363const double g = q_full [(size_t )gi ]; 364const double s = o .gate_sigmoid ?1.0 / (1.0 + std::exp (- g )) :g / (1.0 + std::exp (- g )); 365out [(size_t ) (h * head_dim + d )]= attn [(size_t ) (h * head_dim + d )]* s ; 366 } 367return out ; 368} 369 370/// {f32 bits, the fp16 bits numpy produces for it} interleaved. Generated by 371/// `scripts/_gen_f16_oracle.py` from `np.float16(np.float32(x))`: an oracle that shares no code with 372/// f16_bits.hpp, which is the whole point of the table. 373const uint32_t kOracle []= { 374#include "qsa_oracle_vectors.inc" 375}; 376constexpr int kOracleN = (int ) (sizeof (kOracle ) /sizeof (kOracle [0 ])) /2 ; 377 378}// namespace 379 380int main (int argc ,char ** argv ) { 381 std::setvbuf (stdout ,nullptr ,_IONBF ,0 );// a crash must not swallow what was printed already 382bool selftest = false,dense = false,bench = false; 383for (int i = 1 ;i < argc ;++ i ) { 384const std::string a = argv [i ]; 385if (a == "--selftest" )selftest = true; 386else if (a == "--qsa-dense" )dense = true; 387else if (a == "--bench" )bench = true; 388else { 389 std::fprintf (stderr ,"usage: qsa_parity [--selftest] [--qsa-dense] [--bench]\n" 390" --qsa-dense attend to EVERY cell instead of the indexer's selection\n" 391" (P1.S4's isolation switch; the sparse selection is still run\n" 392" and checked, against the reference's dense/sparse property)\n" 393" --bench time the kernels at 32K of context\n" ); 394return 2 ; 395 } 396 } 397 398const strata::kernels::QsaShapes S = strata::kernels::qsa_real_shapes (); 399const int64_t NH = S .n_head ,NKV = S .n_head_kv ,HD = S .head_dim ,IDXN = S .idx_n_head ,IDXD = S .idx_dim , 400R = S .idx_block ,TOPK = S .idx_top_k ; 401const int64_t MAXC = strata::kernels::kTopkMaxCells ; 402const float EPS = strata::kernels::qsa_rms_eps (); 403const double THETA = strata::kernels::qsa_freq_base (); 404 std::mt19937 rng (20260916u ); 405 std::normal_distribution < double > gauss (0.0 ,1.0 ); 406auto rnd = [& ](double s ) {return (float ) (gauss (rng )* s ); }; 407 408 std::printf ("qsa_parity: n_head %lld n_head_kv %lld head_dim %lld indexer %lldx%lld r=%lld " 409"top_k %lld page (from the shapes) %lld [%s]\n\n" , 410 (long long )NH , (long long )NKV , (long long )HD , (long long )IDXN , (long long )IDXD , 411 (long long )R , (long long )TOPK , (long long )S .page_size ,dense ?"DENSE" :"sparse" ); 412require ("the fixture's r is the artifact's IDX_BLOCK" ,R == REF_R ,"r = " + std::to_string (R )); 413 414// ================= 0. the fp16 converter, against numpy ================= 415 { 416int mism = 0 ,subnormal = 0 ; 417for (int i = 0 ;i < kOracleN ;++ i ) { 418float f ; 419const uint32_t fb = kOracle [2 * i ]; 420 std::memcpy (& f ,& fb ,4 ); 421const uint16_t want = (uint16_t )kOracle [2 * i + 1 ]; 422const uint16_t got = f16_from_f32 (f ); 423if (got != want ) { 424if (mism < 5 ) std::printf (" f32 0x%08X -> got 0x%04X, numpy says 0x%04X\n" ,fb ,got ,want ); 425++ mism ; 426 } 427if ((want & 0x7C00u )== 0u && (want & 0x3FFu )!= 0u )++ subnormal ; 428 } 429require ("f32->f16 matches numpy's float16 on every vector" ,mism == 0 , 430 std::to_string (kOracleN )+ " vectors, " + std::to_string (subnormal )+ " subnormal" ); 431int bad_rev = 0 ; 432for (int h = 0 ;h < 65536 ;++ h ) { 433const int ex = (h >>10 )& 0x1F ,man = h & 0x3FF ; 434if (ex == 31 )continue ;// inf/NaN come from the vector table above 435const double mag = ex == 0 ? (double )man * std::ldexp (1.0 ,-24 ) 436 : (double ) (1024 + man )* std::ldexp (1.0 ,ex - 25 ); 437const double want = (h & 0x8000 ) ?- mag :mag ; 438if ((double )f32_from_f16 ((uint16_t )h )!= want ) { 439if (bad_rev < 5 ) std::printf (" f16 0x%04X -> %.9g, want %.9g\n" ,h , (double )f32_from_f16 ((uint16_t )h ),want ); 440++ bad_rev ; 441 } 442 } 443require ("f16->f32 is exact on all 65,536 bit patterns" ,bad_rev == 0 , 444 std::to_string (bad_rev )+ " wrong" ); 445 } 446 447// ================= 1. kv_append: the paged pool, three page granules ================= 448const int64_t TCELLS = 1100 ;// 275 indexer blocks, and 3 pages at page_size 512 449 std::vector < float > kcur_all ((size_t )TCELLS * NKV * HD ),vcur_all ((size_t )TCELLS * NKV * HD ); 450for (auto & x :kcur_all )x = rnd (1.0 ); 451for (auto & x :vcur_all )x = rnd (1.0 ); 452// EVERY pointer this kernel set takes is a DEVICE pointer - the append sources, the indexer weights 453// and the rope tables alike. The first draft passed `&kcur_all[...]`, `w_kn.data()` and 454// `cos_tab.data()` straight through, and every kernel that dereferenced one took an illegal access. 455Dev < float > dkcur_all ,dvcur_all ; 456dkcur_all .put (kcur_all ); 457dvcur_all .put (vcur_all ); 458 459struct PageCase { 460int64_t page_size = 0 ,n_pages = 0 ; 461 std::vector < int32_t > table ; 462 }; 463 std::vector < PageCase > pages ; 464for (int64_t ps : {(int64_t )1 , (int64_t )4 , (int64_t )512 }) { 465PageCase c ; 466c .page_size = ps ; 467c .n_pages = (TCELLS + ps - 1 ) /ps ; 468c .table .resize ((size_t )c .n_pages ); 469for (int64_t i = 0 ;i < c .n_pages ;++ i )c .table [(size_t )i ]= (int32_t ) (c .n_pages - 1 - i );// REVERSED 470pages .push_back (std::move (c )); 471 } 472const std::vector < int32_t > ids = {0 ,1 ,2 ,3 ,5 ,8 ,13 ,21 ,34 ,39 ,1099 ,700 }; 473 474for (PageCase & c :pages ) { 475// THE PAGE GRANULE IS A PROPERTY OF THE SHAPES, and the kernel takes it from there rather than from an 476// argument. The first version of this fixture left it at 512 while the table described 1-cell pages, 477// so the kernel indexed a 1100-page table as if it had 3 pages and ran off the pool - which is what an 478// illegal memory access reported. A test that feeds one geometry and expects another is measuring 479// itself; the fix is to build the shapes per case. 480 strata::kernels::QsaShapes Sc = S ; 481Sc .page_size = c .page_size ; 482const size_t pool_n = (size_t )c .n_pages * NKV * c .page_size * HD ; 483Dev < uint16_t > dk (pool_n ),dv (pool_n ); 484Dev < int32_t > dtab ; 485dtab .put (c .table ); 486for (int64_t t = 0 ;t < TCELLS ;++ t ) 487 strata::kernels::kv_append (dk .p ,dv .p ,dtab .p ,t ,dkcur_all .p + (size_t )t * NKV * HD , 488dvcur_all .p + (size_t )t * NKV * HD ,Sc ,nullptr ); 489const std::vector < uint16_t > hk = dk .get (pool_n ),hv = dv .get (pool_n ); 490 491int mism = 0 ,mism_linear = 0 ,mism_head_major = 0 ; 492const int64_t rows_avail = (int64_t ) (pool_n / (size_t )HD ); 493// A rival layout's address is HYPOTHETICAL: where it would put the value may be outside the pool, 494// and reading there is a host access violation rather than a mismatch. Off the end counts as 495// "the value is not where the rival would put it", which is the claim being tested. 496auto elsewhere = [& ](int64_t r ) {return r < 0 || r >=rows_avail ; }; 497for (int64_t cell = 0 ;cell < TCELLS ;++ cell ) 498for (int64_t h = 0 ;h < NKV ;++ h ) 499for (int64_t d = 0 ;d < HD ;++ d ) { 500const size_t src = (size_t ) (cell * NKV + h )* HD + d ; 501const uint16_t wk = f16_from_f32 (kcur_all [src ]),wv = f16_from_f32 (vcur_all [src ]); 502// the DECLARED layout: [page][kv_head][page_size][head_dim] 503const int64_t row = ((int64_t )c .table [(size_t ) (cell /c .page_size )]* NKV + h )* c .page_size + 504 (cell %c .page_size ); 505if (hk [(size_t )row * HD + d ]!= wk || hv [(size_t )row * HD + d ]!= wv )++ mism ; 506// rival (a): the page table ignored, i.e. written at the logical address 507const int64_t rl = (cell * NKV + h )* c .page_size + (cell %c .page_size ); 508if (elsewhere (rl )|| hk [(size_t )rl * HD + d ]!= wk )++ mism_linear ; 509// rival (b): cell-major inside the page instead of head-major 510const int64_t rh = ((int64_t )c .table [(size_t ) (cell /c .page_size )]* c .page_size + 511 (cell %c .page_size ))* NKV + h ; 512if (elsewhere (rh )|| hk [(size_t )rh * HD + d ]!= wk )++ mism_head_major ; 513 } 514const double n_tot = (double ) (TCELLS * NKV * HD ); 515require ("kv_append at page_size " + std::to_string (c .page_size )+ ": the pool is BIT-EXACT" , 516mism == 0 , std::to_string (mism )+ " of " + std::to_string ((long long )n_tot )+ " bits wrong" ); 517verdict (" the page table is observable at page_size " + std::to_string (c .page_size ), 518 (double )mism_linear /n_tot > 0.5 , 519pct ((double )mism_linear /n_tot )+ " (linear vs declared)" ); 520// The head-major rival is IDENTICAL to the declared layout when page_size == 1 (both reduce to 521// `cell * n_head_kv + h`), so the separation is only asserted where the layouts actually differ. 522if (c .page_size >=4 ) { 523verdict (" head-major-in-page is observable at page_size " + std::to_string (c .page_size ), 524 (double )mism_head_major /n_tot > 0.5 , 525pct ((double )mism_head_major /n_tot )+ " (cell-major vs head-major)" ); 526 } 527 528Dev < int32_t > dids ; 529dids .put (ids ); 530const size_t scr_n = ids .size ()* NKV * HD ; 531Dev < uint16_t > dks (scr_n ),dvs (scr_n ); 532 strata::kernels::kv_gather (dk .p ,dv .p ,dtab .p ,dids .p , (int64_t )ids .size (),Sc ,dks .p ,dvs .p ,nullptr ); 533const std::vector < uint16_t > gk = dks .get (scr_n ),gv = dvs .get (scr_n ); 534int gm = 0 ; 535for (size_t j = 0 ;j < ids .size ();++ j ) 536for (int64_t h = 0 ;h < NKV ;++ h ) 537for (int64_t d = 0 ;d < HD ;++ d ) { 538const size_t src = (size_t ) (ids [j ]* NKV + h )* HD + d ; 539if (gk [(size_t ) (j * NKV + h )* HD + d ]!= f16_from_f32 (kcur_all [src ]))++ gm ; 540if (gv [(size_t ) (j * NKV + h )* HD + d ]!= f16_from_f32 (vcur_all [src ]))++ gm ; 541 } 542require (" kv_gather is BIT-EXACT at page_size " + std::to_string (c .page_size ),gm == 0 , 543 std::to_string (gm )+ " wrong bits" ); 544 } 545 546// ================= 2. indexer_key_append ================= 547const int64_t NT = 10 ;// 2 complete blocks + a 2-cell tail 548// The cells sit at POSITIONS 100..109, not at 0..9: `QsaCache.pos` is what the reference rotates by, 549// and a kernel that assumes position == cell index is wrong for any sequence that does not start at 0 550// (prefix reuse, phase 5). With base 100 the two readings are 514% apart, which is asserted below. 551const int32_t POS_BASE = 100 ; 552RefCache rc ; 553 std::vector < float > raw_flat ; 554for (int64_t t = 0 ;t < NT ;++ t ) { 555 std::vector < double > kk ((size_t ) (NKV * HD )),vv ((size_t ) (NKV * HD )),rr ((size_t )IDXD ); 556for (int64_t i = 0 ;i < NKV * HD ;++ i ) {kk [(size_t )i ]= gauss (rng );vv [(size_t )i ]= gauss (rng ); } 557// cell MAGNITUDES 1, 4, 16, 64 - for the same reason round 196 gave its residual streams different 558// scales: four i.i.d. rows of normal noise have nearly the same norm by accident, so "pool then norm" 559// and "norm then pool" would agree to within the noise and the fixture could not see its own trap. 560for (int64_t d = 0 ;d < IDXD ;++ d )rr [(size_t )d ]= gauss (rng )* std::pow (4.0 , (double ) (t %4 )); 561for (int64_t d = 0 ;d < IDXD ;++ d )raw_flat .push_back ((float )rr [(size_t )d ]); 562// The reference gets the f32 PROMOTION of what the device gets, not the f64 original. Feeding it 563// the f64 values left a 6e-8 relative difference, which is invisible in a score but crosses an f32 564// rounding boundary in one value in four - and the spare key is asserted BIT-EXACT. 565for (int64_t d = 0 ;d < IDXD ;++ d )rr [(size_t )d ]= (double )raw_flat [(size_t )t * IDXD + d ]; 566rc .append (kk ,vv ,rr , (double ) (100 + t )); 567 } 568 std::vector < float > w_kn ((size_t )IDXD ); 569for (auto & x :w_kn )x = 1.0f + 0.1f * rnd (1.0 ); 570 std::vector < float > cos_tab ((size_t ) (2000 * S .n_rot /2 )),sin_tab (cos_tab .size ()); 571 strata::kernels::build_rope_table ((int )S .n_rot ,THETA ,2000 ,cos_tab .data (),sin_tab .data ()); 572Dev < float > dw_kn ,dcos ,dsin ; 573dw_kn .put (w_kn ); 574dcos .put (cos_tab ); 575dsin .put (sin_tab ); 576 577const int64_t n_bid = NT /R ; 578const size_t pooled_n = (size_t ) (n_bid + 1 )* IDXD ; 579Dev < float > dpooled (pooled_n ),ddead ((size_t )IDXD ),dtail ((size_t ) (R - 1 )* IDXD ); 580Dev < int32_t > dblockpos (1 );// the rotation position, which only the DEVICE may read 581// The POSITION is a device value now, because a host scalar would be baked into a captured graph. One 582// `cudaMemcpy` per cell here; the layer keeps this buffer and updates it per token. 583Dev < int32_t > dpos (1 ); 584 { 585 strata::kernels::QsaIndexerBuffers bufs {dtail .p ,ddead .p ,dpooled .p ,dblockpos .p }; 586Dev < float > draw ((size_t )IDXD ); 587for (int64_t t = 0 ;t < NT ;++ t ) {// one cell at a time: the tail is a ring and the spare row MOVES 588check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()) 589 .memcpy (draw .p , 590& raw_flat [(size_t )t * IDXD ], 591 (size_t )IDXD * 4 ) 592 .wait ()), 593"raw" ); 594const int32_t tpos = (int32_t )t ; 595check ( 596DPCT_CHECK_ERROR ( 597 (dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy (dpos .p ,& tpos ,4 ).wait ()), 598"pos" ); 599 strata::kernels::indexer_key_append (draw .p ,dpos .p ,POS_BASE ,dw_kn .p ,EPS ,bufs ,S ,dcos .p ,dsin .p , 600nullptr ); 601 } 602const std::vector < float > got = dpooled .get (pooled_n ),got_dead = ddead .get ((size_t )IDXD ); 603 std::vector < double > terms ; 604const std::vector < double > want = ref_pooled (rc ,w_kn ,EPS , (int )S .n_rot ,THETA ,Alt {},& terms ); 605const std::vector < double > want_raw = ref_pooled_raw (rc ); 606 607// (a) the spare slot: BIT-EXACT, because rope at position 0 is the identity in both (cos = 1, sin = 0 608// exactly), so the residual the pooled rows carry from the f32 rope cannot appear here. 609int dead_bad = 0 ; 610for (int64_t d = 0 ;d < IDXD ;++ d ) 611if (got_dead [(size_t )d ]!= (float )want [(size_t )n_bid * IDXD + d ])++ dead_bad ; 612require ("the spare slot's key (rms_norm of cell 0) is BIT-EXACT" ,dead_bad == 0 , 613 std::to_string (dead_bad )+ " of " + std::to_string (IDXD )+ " wrong" ); 614require ("the spare slot is at row n_bid and nowhere else" ,n_bid == 2 , 615"10 cells / r=4 -> 2 complete blocks" ); 616 617// (b) the pooled blocks against the reference 618// THE DENOMINATOR IS THE ROPE'S TERMS, not the result: `a*cos - b*sin` cancels, and the kernel's 619// rotation runs in f32 over an f32 table (6e-8 per term) while the reference's runs in f64. Dividing 620// by the result reports the cancellation, which is what made this read 1.067e-06 against a 1e-6 bar. 621double worst = 0 ; 622for (int64_t b = 0 ;b < n_bid ;++ b ) 623for (int64_t d = 0 ;d < IDXD ;++ d ) { 624const double wv = want [(size_t )b * IDXD + d ]; 625const double tm = terms [(size_t )b * IDXD + d ]; 626worst = std::max (worst ,rel_terms (wv , (double )got [(size_t )b * IDXD + d ],tm )); 627 } 628report ("pooled block keys vs the reference" ,worst ,"rel/|rope terms|" ); 629if (!(worst <=1e-6 )) { std::printf (" *** over 1e-6 ***\n" );++ g_bad ; } 630 631// (c) THE INCOMPLETE TAIL IS NOT POOLED: the two tail cells take the SPARE slot's score, which is cell 632// 0's key - not their own mean. A rival reading that pools them would still fill every row. 633 { 634 std::vector < double > tm ((size_t )IDXD ,0.0 ); 635for (int64_t i = n_bid * R ;i < NT ;++ i ) 636for (int64_t d = 0 ;d < IDXD ;++ d )tm [(size_t )d ]+= rc .raw [(size_t )i ][(size_t )d ] /2.0 ; 637ref_rms_norm (tm ,w_kn ,EPS ); 638double num = 0 ,den = 0 ; 639for (int64_t d = 0 ;d < IDXD ;++ d ) { 640num += std::fabs (tm [(size_t )d ]- (double )got_dead [(size_t )d ]); 641den += std::fabs (tm [(size_t )d ]); 642 } 643verdict ("the incomplete tail is NOT pooled into the spare slot" ,num /den > 0.5 ,pct (num /den )); 644 } 645 646auto sep = [& ](const std::string & name ,const Alt & a ) { 647const std::vector < double > alt = ref_pooled (rc ,w_kn ,EPS , (int )S .n_rot ,THETA ,a ); 648double num = 0 ,den = 0 ; 649// Rows 0..n_bid INCLUSIVE: the spare slot is row n_bid and three of the four rivals change 650// nothing else, so leaving it out made "the spare key from the LAST raw key" separate 0.00%. 651for (int64_t b = 0 ;b <=n_bid ;++ b ) 652for (int64_t d = 0 ;d < IDXD ;++ d ) { 653num += std::fabs (alt [(size_t )b * IDXD + d ]- want [(size_t )b * IDXD + d ]); 654den += std::fabs (want [(size_t )b * IDXD + d ]); 655 } 656verdict (name ,num /den > 0.05 ,pct (num /den )); 657 }; 658Alt a1 ;a1 .rotate_at_block_start = false; 659sep ("rotating at the block's LAST cell is observable" ,a1 ); 660Alt a2 ;a2 .pool_then_norm = false; 661sep ("norm-then-pool vs pool-then-norm is observable" ,a2 ); 662Alt a3 ;a3 .dead_from_first = false; 663sep ("the spare key from the LAST raw key is observable" ,a3 ); 664Alt a4 ;a4 .rope_raw = true; 665sep ("rotating the RAW indexer keys is observable" ,a4 ); 666 {// THE POSITION BASE. The same reference with the cells at 0..9 instead of 100..109 - i.e. 667// what a kernel that equates a cell's position with its index would compute. 668RefCache flat = rc ; 669for (int64_t j = 0 ;j < NT ;++ j )flat .pos [(size_t )j ]= (double )j ; 670const std::vector < double > alt = ref_pooled (flat ,w_kn ,EPS , (int )S .n_rot ,THETA ,Alt {}); 671double num = 0 ,den = 0 ; 672for (int64_t b = 0 ;b <=n_bid ;++ b ) 673for (int64_t d = 0 ;d < IDXD ;++ d ) { 674num += std::fabs (alt [(size_t )b * IDXD + d ]- want [(size_t )b * IDXD + d ]); 675den += std::fabs (want [(size_t )b * IDXD + d ]); 676 } 677verdict ("the rotation's POSITION BASE (pos_base) is observable" ,num /den > 0.05 , 678pct (num /den )); 679 } 680 681// (d) THE TRAP THIS FIXTURE CANNOT SEE, measured and reported rather than hidden. `rms_norm` divides 682// by sqrt(mean(x^2) + eps), so the 1/r in the mean cancels EXCEPT through eps: mean and sum differ 683// by ~eps/(2*mean(x^2)) relative. `ref/qsa.py` L463-465 makes the same point about its own test. 684 { 685 std::vector < double > psum = want_raw ; 686for (auto & x :psum )x *= (double )R ; 687 std::vector < double > nm = want_raw ,ns = psum ; 688for (int64_t b = 0 ;b < n_bid ;++ b ) { 689 std::vector < double > m (nm .begin ()+ (size_t )b * IDXD ,nm .begin ()+ (size_t ) (b + 1 )* IDXD ); 690 std::vector < double > s (ns .begin ()+ (size_t )b * IDXD ,ns .begin ()+ (size_t ) (b + 1 )* IDXD ); 691ref_rms_norm (m ,w_kn ,EPS ); 692ref_rms_norm (s ,w_kn ,EPS ); 693for (int64_t d = 0 ;d < IDXD ;++ d ) { 694nm [(size_t )b * IDXD + d ]= m [(size_t )d ]; 695ns [(size_t )b * IDXD + d ]= s [(size_t )d ]; 696 } 697 } 698double num = 0 ,den = 0 ; 699for (size_t i = 0 ;i < want_raw .size ();++ i ) { 700num += std::fabs (psum [i ]- want_raw [i ]); 701den += std::fabs (want_raw [i ]); 702 } 703verdict ("the 1/r divisor IS observable in the RAW pooled value" ,num /den > 0.5 , 704pct (num /den )+ " (sum vs mean, before any norm)" ); 705 std::printf (" %-48s %.3e <-- below EVERY score tolerance; the divisor cannot be\n" , 706"the same divisor AFTER the norm" ,rel_l1 (ns ,nm )); 707 std::printf (" %-48s %s\n" ,"" ,"checked downstream at all, which is why the raw value is the" ); 708 std::printf (" %-48s %s\n" ,"" ,"only place the mean/sum question is answerable." ); 709 } 710 } 711 712// ================= 3. qsa_index ================= 713 std::vector < float > q_idx ((size_t ) (IDXN * IDXD )); 714for (auto & x :q_idx )x = rnd (1.0 ); 715// A bias of ~0.4 against scores of ~20 separates "applies the bias" from "drops it" by 3.4%, which 716// is not a fixture that can see its own trap. This is a guard for the kernel's optional additional 717// bias, separate from the mandatory incomplete-tail bias; it is sized to 718// be comparable with the scores so that dropping it is material. 719 std::vector < float > bias ((size_t ) (n_bid + 1 )); 720for (auto & x :bias )x = rnd (8.0f ); 721 { 722const std::vector < float > got_pooled = dpooled .get (pooled_n ); 723const std::vector < double > p64 = as_d (got_pooled ); 724const std::vector < double > q_idx64 = as_d (q_idx ); 725const int64_t n_kv = NT ; 726Dev < float > dp ,dqi ,dbias ,dsc ; 727dp .put (got_pooled ); 728dqi .put (q_idx ); 729dbias .put (bias ); 730dsc .alloc ((size_t )n_kv ); 731 strata::kernels::qsa_index (dp .p ,n_bid ,dqi .p ,dbias .p ,S ,n_kv ,dsc .p ,nullptr ); 732const std::vector < float > got = dsc .get ((size_t )n_kv ); 733const std::vector < double > want = 734ref_indexer_scores (p64 ,n_bid ,q_idx64 ,IDXN ,IDXD ,bias ,n_kv ,Alt {}); 735 736// The score is a SUM of four relu'd dots plus the bias, so the denominator is the magnitude of the 737// TERMS - |dot| bounds a relu'd dot from above and is what is used here. 738double worst = 0 ; 739for (int64_t j = 0 ;j < n_kv ;++ j ) { 740const int64_t cb = std::min (j /R ,n_bid ); 741double terms = std::fabs ((double )bias [(size_t )cb ]); 742if (cb == n_bid && n_kv %R != 0 )terms += 1e9 ; 743for (int64_t h = 0 ;h < IDXN ;++ h ) { 744double dot = 0 ; 745for (int64_t d = 0 ;d < IDXD ;++ d )dot += p64 [(size_t )cb * IDXD + d ]* q_idx64 [(size_t )h * IDXD + d ]; 746terms += std::fabs (dot ); 747 } 748worst = std::max (worst ,rel_terms (want [(size_t )j ], (double )got [(size_t )j ],terms )); 749 } 750report ("indexer cell scores vs the reference" ,worst ,"rel/Sum|terms|" ); 751if (!(worst <=1e-6 )) { std::printf (" *** over 1e-6 ***\n" );++ g_bad ; } 752 753require ("cells of one block share its score (0..3)" , 754got [0 ]== got [1 ]&& got [1 ]== got [2 ]&& got [2 ]== got [3 ]&& got [0 ]!= got [4 ]); 755require ("cells 8,9 (the tail) take the SPARE slot's score, not block 1's" , 756got [8 ]== got [9 ]&& got [9 ]!= got [7 ],"got[8] == got[9] != got[7]" ); 757 758auto sep_scores = [& ](const std::string & name ,const Alt & a ) { 759const std::vector < double > alt = ref_indexer_scores (p64 ,n_bid ,q_idx64 ,IDXN ,IDXD ,bias ,n_kv ,a ); 760double num = 0 ,den = 0 ; 761// The mandatory tail bias must not swamp the score-arithmetic fixture. 762for (int64_t j = 0 ;j < n_bid * R ;++ j ) { 763num += std::fabs (alt [(size_t )j ]- want [(size_t )j ]); 764den += std::fabs (want [(size_t )j ]); 765 } 766verdict (name ,num /den > 0.05 ,pct (num /den )); 767 }; 768Alt a5 ;a5 .relu_per_head = false; 769sep_scores ("relu PER HEAD vs relu(sum of heads) is observable" ,a5 ); 770Alt a6 ;a6 .use_relu = false; 771sep_scores ("dropping the relu is observable" ,a6 ); 772Alt a7 ;a7 .use_bias = false; 773sep_scores ("dropping the per-block bias is observable" ,a7 ); 774 } 775 776// Causal decode's incomplete tail must survive even when its dot-product score 777// ties every completed block. The oracle supplies +1e9 in set_input_qsa; 778// without it, ascending-index top-k drops every tail after the sparse switch. 779// Replay one captured graph across block/page boundaries to catch stale bias. 780 { 781const int64_t max_n = 20480 ; 782const int64_t max_blocks = max_n /R + 1 ; 783const int64_t cap = strata::kernels::qsa_selection_width (max_n ,S ); 784Dev < float > pooled ,query ,scores ((size_t )max_n ); 785Dev < int32_t > ids ((size_t )cap ),step (strata::kernels::kStepCount ); 786pooled .put (std::vector < float > ((size_t )max_blocks * IDXD ,0.0f )); 787query .put (std::vector < float > ((size_t )IDXN * IDXD ,0.0f )); 788 789 dpct::queue_ptr stream ; 790 dpct::experimental::command_graph_ptr graph ; 791 dpct::experimental::command_graph_exec_ptr exec ; 792check (DPCT_CHECK_ERROR ( 793stream = dpct::get_current_device ().create_queue (true)), 794"tail stream" ); 795check (DPCT_CHECK_ERROR (dpct::experimental::begin_recording (stream )), 796"tail capture begin" ); 797 strata::kernels::qsa_index_step (pooled .p ,query .p ,nullptr ,S ,step .p ,max_blocks ,scores .p ,stream ); 798 strata::kernels::topk_512_step (scores .p ,S ,cap ,step .p ,ids .p ,stream ); 799check ( 800DPCT_CHECK_ERROR (dpct::experimental::end_recording (stream ,& graph )), 801"tail capture end" ); 802check (DPCT_CHECK_ERROR ( 803exec = new sycl::ext::oneapi::experimental::command_graph < 804 sycl::ext::oneapi::experimental::graph_state::executable > ( 805graph -> finalize ())), 806"tail instantiate" ); 807 808const std::vector < int64_t > counts = { 8091 ,2 ,3 ,4 ,511 ,512 ,513 ,2046 ,2047 ,2048 ,2049 ,2050 ,2051 , 8102052 ,2053 ,2054 ,2055 ,2056 ,2057 ,2058 ,2059 ,2060 , 8114095 ,4096 ,4097 ,8191 ,8192 ,8193 ,20477 ,20478 ,20479 ,20480 }; 812for (const int64_t n :counts ) { 813const int64_t width = strata::kernels::qsa_selection_width (n ,S ); 814const int64_t tail = n %R ; 815 std::vector < int32_t > want ; 816for (int64_t j = 0 ;j < width - tail ;++ j )want .push_back ((int32_t )j ); 817for (int64_t j = n - tail ;j < n ;++ j )want .push_back ((int32_t )j ); 818 819 strata::kernels::qsa_index (pooled .p ,n /R ,query .p ,nullptr ,S ,n ,scores .p ,nullptr ); 820 strata::kernels::topk_512 (scores .p ,n ,S ,cap ,ids .p ,nullptr ); 821require ("tail static n=" + std::to_string (n ),ids .get ((size_t )width )== want ); 822 823 std::vector < int32_t > values (strata::kernels::kStepCount ); 824 strata::kernels::qsa_step_fill (values .data (),n - 1 ,S ); 825step .put (values ); 826check (DPCT_CHECK_ERROR (stream -> ext_oneapi_graph (* exec )), 827"tail replay" ); 828check (DPCT_CHECK_ERROR (stream -> wait ()),"tail replay sync" ); 829require ("tail captured n=" + std::to_string (n ),ids .get ((size_t )width )== want ); 830const auto actual_scores = scores .get ((size_t )n ); 831bool exact_scores = true; 832for (int64_t j = 0 ;j < n ;++ j ) { 833const float expected = j >=n - tail ?1e9f :0.0f ; 834exact_scores = exact_scores && actual_scores [(size_t )j ]== expected ; 835 } 836require (" only incomplete cells receive the bias" ,exact_scores ); 837 } 838check (DPCT_CHECK_ERROR (delete (exec )),"tail exec destroy" ); 839check (DPCT_CHECK_ERROR (delete (graph )),"tail graph destroy" ); 840check ( 841DPCT_CHECK_ERROR (dpct::get_current_device ().destroy_queue (stream )), 842"tail stream destroy" ); 843 } 844 845// ================= 4. topk_512, against an independent sort ================= 846 { 847const int64_t CAP = strata::kernels::qsa_selection_width (MAXC ,S ); 848Dev < float > dsc ; 849Dev < int32_t > dids ; 850dsc .alloc ((size_t )MAXC ); 851dids .alloc ((size_t )CAP ); 852 std::vector < float > sc ((size_t )MAXC ); 853 854auto one = [& ](const std::string & name ,int64_t n_kv ) { 855dsc .put (std::vector < float > (sc .begin (),sc .begin ()+ n_kv )); 856 strata::kernels::topk_512 (dsc .p ,n_kv ,S ,CAP ,dids .p ,nullptr ); 857const int64_t width = strata::kernels::qsa_selection_width (n_kv ,S ); 858const std::vector < int32_t > g = dids .get ((size_t )width ); 859const std::vector < int32_t > want = ref_select (as_d (std::vector < float > (sc .begin (),sc .begin ()+ n_kv )), 860n_kv ,TOPK , false); 861const bool ok = g == want ; 862require (name ,ok , std::to_string (width )+ " ids, width = min(n_kv, top_k + r - 1)" ); 863if (!ok ) { 864for (size_t i = 0 ;i < std::min (g .size (),want .size ());++ i ) 865if (g [i ]!= want [i ]) { 866 std::printf (" first difference at %zu: got %d, want %d\n" ,i ,g [i ],want [i ]); 867break ; 868 } 869 } 870bool asc = true; 871for (size_t i = 1 ;i < g .size ();++ i )if (g [i ] <=g [i - 1 ])asc = false; 872require (" ...ascending and unique" ,asc ); 873return g ; 874 }; 875 876for (auto & x :sc )x = rnd (1.0 ); 877one ("topk_512 n_kv = 1" ,1 ); 878one ("topk_512 n_kv = 7 (random)" ,7 ); 879one ("topk_512 n_kv = 2048 (the plan's threshold)" ,2048 ); 880one ("topk_512 n_kv = 2051 (the reference's own bound)" ,2051 ); 881one ("topk_512 n_kv = 2052 (two past the plan's number)" ,2052 ); 882one ("topk_512 n_kv = 5000 (random)" ,5000 ); 883one ("topk_512 n_kv = 32768 (= kTopkMaxCells)" ,MAXC ); 884 885// ALL-EQUAL scores: every cell ties, so the answer must be 0..width-1 and any other tie rule shows up 886// on the first element. ggml does not specify the rule; the reference and the kernel both say 887// ascending index, and this is the case that distinguishes them. 888 std::fill (sc .begin (),sc .begin ()+ 2052 ,0.25f ); 889one ("topk_512 with 2052 EQUAL scores (every cell ties)" ,2052 ); 890 891// a tie BLOCK straddling the cut: 100 cells share the cut score and only some of them fit 892for (int64_t j = 0 ;j < 5000 ;++ j )sc [(size_t )j ]= (float ) (- (double )j ); 893for (int64_t j = 2051 - 50 ;j < 2051 + 50 ;++ j )sc [(size_t )j ]= -1000.0f ; 894one ("topk_512 with a 100-cell tie straddling the cut" ,5000 ); 895 896// THE IDENTITY BELOW THE BOUND. `select_cells` returns `arange` whenever width == n_kv, which is what 897// "selection skipped when context <= 2,048" means - and it holds to 2,051, not 2,048. 898for (int64_t n : {(int64_t )2048 , (int64_t )2051 }) { 899for (int64_t j = 0 ;j < n ;++ j )sc [(size_t )j ]= rnd (1.0 ); 900const std::vector < int32_t > g = one (std::string ("topk_512 n_kv = " )+ std::to_string (n )+ 901" selects every cell (identity)" , 902n ); 903bool ident = (int64_t )g .size ()== n ; 904for (int64_t j = 0 ;j < n && ident ;++ j )if (g [(size_t )j ]!= j )ident = false; 905require (" ...and it really is 0,1,2,..." ,ident ); 906 } 907 {// one past the bound the identity must FAIL, or the two checks above prove nothing 908for (int64_t j = 0 ;j < 2052 ;++ j )sc [(size_t )j ]= rnd (1.0 ); 909const std::vector < int32_t > g = one ("topk_512 n_kv = 2052 is NOT the identity" ,2052 ); 910 std::vector < char > kept (2052 ,0 ); 911for (int32_t id :g )kept [(size_t )id ]= 1 ; 912int64_t missing = 0 ; 913for (int64_t j = 0 ;j < 2052 ;++ j )if (!kept [(size_t )j ])++ missing ; 914int64_t argmin = 0 ; 915for (int64_t j = 1 ;j < 2052 ;++ j )if (sc [(size_t )j ]< sc [(size_t )argmin ])argmin = j ; 916require (" ...exactly one cell is dropped, and it is the smallest score" , 917missing == 1 && !kept [(size_t )argmin ], std::to_string (missing )+ " dropped" ); 918 } 919 } 920 921// ================= 5. qsa_attend on the loud-cell fixture ================= 922// `ref/qsa.py` PROPERTY 8's own numbers: a key with 100 in its first dim against zeros, a value of 10 923// against 1, and q[:,0] = 1. The logit gap is 100/sqrt(256) = 6.25, so the loud cell takes ~99% of its 924// head's weight - and exactly zero when it is not in the selected set. 925 { 926const int64_t N = 8 ; 927 std::vector < std::vector < double >> k2 ,v2 ; 928 std::vector < float > k2f ,v2f ; 929for (int64_t j = 0 ;j < N ;++ j ) { 930 std::vector < double > kk ((size_t ) (NKV * HD ),0.0 ),vv ((size_t ) (NKV * HD ),0.0 ); 931for (int64_t h = 0 ;h < NKV ;++ h )vv [(size_t ) (h * HD )]= 1.0 ; 932kk [0 ]= j == N - 1 ?100.0 :0.0 ; 933vv [0 ]= j == N - 1 ?10.0 :1.0 ; 934for (int64_t i = 0 ;i < NKV * HD ;++ i ) {k2f .push_back ((float )kk [(size_t )i ]);v2f .push_back ((float )vv [(size_t )i ]); } 935k2 .push_back (kk ); 936v2 .push_back (vv ); 937 } 938 std::vector < double > q ((size_t ) (NH * HD ),0.0 ); 939for (int64_t h = 0 ;h < NH ;++ h )q [(size_t ) (h * HD )]= 1.0 ; 940 941Dev < float > dq ; 942dq .put (as_f (q )); 943const size_t scr = (size_t )N * NKV * HD ; 944 std::vector < uint16_t > kbits (scr ),vbits (scr ); 945for (size_t i = 0 ;i < scr ;++ i ) {kbits [i ]= f16_from_f32 (k2f [i ]);vbits [i ]= f16_from_f32 (v2f [i ]); } 946Dev < uint16_t > dks (scr ),dvs (scr ); 947dks .put (kbits ); 948dvs .put (vbits ); 949Dev < float > dattn ((size_t )NH * HD ),dwt ((size_t )NH * N ); 950 951 std::vector < int32_t > all (N ),no_loud (N - 1 ); 952for (int64_t j = 0 ;j < N ;++ j )all [(size_t )j ]= (int32_t )j ; 953for (int64_t j = 0 ;j < N - 1 ;++ j )no_loud [(size_t )j ]= (int32_t )j ; 954 955// the scratch is written directly here (no pool), so this section is about the attention alone 956 strata::kernels::qsa_attend (dq .p ,dks .p ,dvs .p ,N ,S ,dattn .p ,dwt .p ,nullptr ); 957const std::vector < double > out_all = as_d (dattn .get ((size_t )NH * HD )); 958 strata::kernels::qsa_attend (dq .p ,dks .p ,dvs .p ,N - 1 ,S ,dattn .p ,nullptr ,nullptr ); 959const std::vector < double > out_sel = as_d (dattn .get ((size_t )NH * HD )); 960const std::vector < double > wts = as_d (dwt .get ((size_t )NH * N )); 961 962verdict ("with every cell selected the loud cell dominates its head 0" ,out_all [0 ]> 5.0 , 963"out[0][0] = " + std::to_string (out_all [0 ]).substr (0 ,6 )); 964require ("with the loud cell unselected it contributes EXACTLY nothing" , 965 std::fabs (out_sel [0 ]- 1.0 )< 1e-6 ,"out[0][0] = " + std::to_string (out_sel [0 ]).substr (0 ,8 )); 966double worst_sum = 0 ; 967for (int64_t h = 0 ;h < NH ;++ h ) { 968double s = 0 ; 969for (int64_t j = 0 ;j < N ;++ j )s += wts [(size_t ) (h * N + j )]; 970worst_sum = std::max (worst_sum , std::fabs (s - 1.0 )); 971 } 972report ("the returned weights sum to 1 per head" ,worst_sum ,"max |1 - sum|" ); 973 974auto sep_attend = [& ](const std::string & name ,const Alt & a ) { 975const std::vector < double > alt = ref_attend (q ,NH ,NKV ,HD ,all ,k2 ,v2 ,a ,nullptr ); 976double num = 0 ,den = 0 ; 977for (size_t i = 0 ;i < alt .size ();++ i ) { 978num += std::fabs (alt [i ]- out_all [i ]); 979den += std::fabs (alt [i ]); 980 } 981verdict (name ,num /den > 0.05 ,pct (num /den )); 982 }; 983Alt a8 ;a8 .kv_divide = false; 984sep_attend ("q % 2 vs q / 12 for the kv head is observable" ,a8 ); 985// The scale trap is NOT asserted on this fixture: its softmax is saturated (the loud cell holds 99% 986// of the weight, so removing a 16x logit scale moves it to 100% and the output by 1.09%). It is 987// asserted on the random 2100-cell fixture below, where the logits are O(10) and the temperature 988// actually matters. This is round 196's lesson about a fixture that cannot see its own trap. 989 std::printf (" %-48s %-6s %s\n" ," (the scale trap is measured on the random fixture)" ,"--" , 990"this fixture's softmax is saturated" ); 991 {// the mask: the same reference with and without the loud cell in the selected set 992const std::vector < double > with_loud = ref_attend (q ,NH ,NKV ,HD ,all ,k2 ,v2 ,Alt {},nullptr ); 993const std::vector < double > without = ref_attend (q ,NH ,NKV ,HD ,no_loud ,k2 ,v2 ,Alt {},nullptr ); 994double num = 0 ,den = 0 ; 995for (size_t i = 0 ;i < with_loud .size ();++ i ) { 996num += std::fabs (with_loud [i ]- without [i ]); 997den += std::fabs (with_loud [i ]); 998 } 999verdict ("attending to the unselected cell is observable" ,num /den > 0.05 ,pct (num /den )); 1000 } 1001 } 1002 1003// ================= 6. the whole layer at n_kv = 2100, so the selection is genuinely sparse ============= 1004int64_t width = 0 ; 1005 { 1006const int64_t T = 2100 ;// > 2051, so `width` really truncates 1007width = strata::kernels::qsa_selection_width (T ,S ); 1008 std::vector < float > pk ((size_t )T * NKV * HD ),pv ((size_t )T * NKV * HD ),praw ((size_t )T * IDXD ); 1009 std::vector < std::vector < double >> k16 ((size_t )T ),v16 ((size_t )T ); 1010RefCache pc ; 1011 std::vector < float > q ((size_t )NH * HD ); 1012for (auto & x :q )x = rnd (1.0 ); 1013for (int64_t t = 0 ;t < T ;++ t ) { 1014 std::vector < double > kk ((size_t ) (NKV * HD )),vv ((size_t ) (NKV * HD )),rr ((size_t )IDXD ); 1015for (int64_t i = 0 ;i < NKV * HD ;++ i ) { 1016kk [(size_t )i ]= gauss (rng ); 1017vv [(size_t )i ]= gauss (rng ); 1018pk [(size_t )t * NKV * HD + i ]= (float )kk [(size_t )i ]; 1019pv [(size_t )t * NKV * HD + i ]= (float )vv [(size_t )i ]; 1020 } 1021for (int64_t d = 0 ;d < IDXD ;++ d ) { 1022rr [(size_t )d ]= gauss (rng ); 1023praw [(size_t )t * IDXD + d ]= (float )rr [(size_t )d ]; 1024 } 1025for (int64_t i = 0 ;i < NKV * HD ;++ i ) { 1026kk [(size_t )i ]= (double )pk [(size_t )t * NKV * HD + i ];// the f32 the device got 1027vv [(size_t )i ]= (double )pv [(size_t )t * NKV * HD + i ]; 1028 } 1029for (int64_t d = 0 ;d < IDXD ;++ d )rr [(size_t )d ]= (double )praw [(size_t )t * IDXD + d ]; 1030pc .append (kk ,vv ,rr , (double )t ); 1031k16 [(size_t )t ].resize ((size_t ) (NKV * HD )); 1032v16 [(size_t )t ].resize ((size_t ) (NKV * HD )); 1033for (int64_t i = 0 ;i < NKV * HD ;++ i ) { 1034k16 [(size_t )t ][(size_t )i ]= (double )f32_from_f16 (f16_from_f32 (pk [(size_t )t * NKV * HD + i ])); 1035v16 [(size_t )t ][(size_t )i ]= (double )f32_from_f16 (f16_from_f32 (pv [(size_t )t * NKV * HD + i ])); 1036 } 1037 } 1038const int64_t p_nbid = T /R ;// 525 complete blocks; the spare key sits at row 525 1039const int64_t page_size = 64 ,n_pages = (T + page_size - 1 ) /page_size ; 1040 strata::kernels::QsaShapes Sp = S ;// the granule lives in the shapes: see section 1 1041Sp .page_size = page_size ; 1042 std::vector < int32_t > table ((size_t )n_pages ); 1043for (int64_t i = 0 ;i < n_pages ;++ i )table [(size_t )i ]= (int32_t ) (n_pages - 1 - i );// REVERSED 1044 1045Dev < int32_t > dtab ; 1046dtab .put (table ); 1047Dev < float > dpk_all ,dpv_all ; 1048dpk_all .put (pk ); 1049dpv_all .put (pv ); 1050Dev < uint16_t > dpk ((size_t )n_pages * NKV * page_size * HD ),dpv ((size_t )n_pages * NKV * page_size * HD ); 1051for (int64_t t = 0 ;t < T ;++ t ) 1052 strata::kernels::kv_append (dpk .p ,dpv .p ,dtab .p ,t ,dpk_all .p + (size_t )t * NKV * HD , 1053dpv_all .p + (size_t )t * NKV * HD ,Sp ,nullptr ); 1054 1055const size_t ppooled_n = (size_t ) (p_nbid + 1 )* IDXD ; 1056Dev < float > dpp ((size_t )ppooled_n ),dpdead ((size_t )IDXD ),dptail ((size_t ) (R - 1 )* IDXD ); 1057Dev < int32_t > dblockpos2 (1 ); 1058Dev < int32_t > dpos2 (1 ); 1059Dev < float > draw ((size_t )IDXD ); 1060 strata::kernels::QsaIndexerBuffers bufs {dptail .p ,dpdead .p ,dpp .p ,dblockpos2 .p }; 1061for (int64_t t = 0 ;t < T ;++ t ) { 1062check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()) 1063 .memcpy (draw .p ,& praw [(size_t )t * IDXD ], 1064 (size_t )IDXD * 4 ) 1065 .wait ()), 1066"raw" ); 1067const int32_t tpos = (int32_t )t ; 1068check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()) 1069 .memcpy (dpos2 .p ,& tpos ,4 ) 1070 .wait ()), 1071"pos2" ); 1072 strata::kernels::indexer_key_append (draw .p ,dpos2 .p ,0 ,dw_kn .p ,EPS ,bufs ,S ,dcos .p ,dsin .p , 1073nullptr ); 1074 } 1075Dev < float > dqidx ,dsc ; 1076dqidx .put (q_idx ); 1077dsc .alloc ((size_t )T ); 1078 strata::kernels::qsa_index (dpp .p ,p_nbid ,dqidx .p ,nullptr ,S ,T ,dsc .p ,nullptr ); 1079 1080Dev < int32_t > dsel ((size_t )T ); 1081 strata::kernels::topk_512 (dsc .p ,T ,S ,T ,dsel .p ,nullptr ); 1082const std::vector < int32_t > sel_sparse = dsel .get ((size_t )width ); 1083const std::vector < float > pool32 = dpp .get (ppooled_n ); 1084const std::vector < double > pool64 = as_d (pool32 ); 1085const std::vector < double > q_idx64 = as_d (q_idx ); 1086const std::vector < double > sc_want = 1087ref_indexer_scores (pool64 ,p_nbid ,q_idx64 ,IDXN ,IDXD , {},T ,Alt {}); 1088const std::vector < int32_t > sel_want = ref_select (sc_want ,T ,TOPK , false); 1089require ("the selected set matches the reference (2100 cells, width 2051)" ,sel_sparse == sel_want , 1090 std::to_string (width )+ " ids" ); 1091 1092// HOW CLOSE IS THE CUT? `indexer_ids` is an EXACT capture key, so a boundary gap of a few fp32 ulp 1093// would make it sensitive to the accumulation order. The gap is measured in ulp of the cut score. 1094 { 1095 std::vector < char > issel ((size_t )T ,0 ); 1096for (int32_t id :sel_sparse )issel [(size_t )id ]= 1 ; 1097double lo = 1e300 ,hi = -1e300 ; 1098for (int32_t id :sel_sparse )lo = std::min (lo ,sc_want [(size_t )id ]); 1099for (int64_t j = 0 ;j < T ;++ j )if (!issel [(size_t )j ])hi = std::max (hi ,sc_want [(size_t )j ]); 1100if (lo == hi ) { 1101// The cut sits inside a group of cells that all score exactly the same - here 0.0, a relu 1102// signal with all four head dots negative - so nothing but the ascending-index rule decides 1103// which of them survive. A gap metric is undefined there; the tie is the finding. 1104int64_t tied_in = 0 ,tied_out = 0 ; 1105for (int32_t id :sel_sparse )if (sc_want [(size_t )id ]== lo )++ tied_in ; 1106for (int64_t j = 0 ;j < T ;++ j )if (!issel [(size_t )j ]&& sc_want [(size_t )j ]== lo )++ tied_out ; 1107 std::printf (" %-48s THE CUT IS A TIE at %.6f: %lld selected, %lld rejected\n" , 1108"the cut" ,lo , (long long )tied_in , (long long )tied_out ); 1109require (" ...and the kernel picks the same ones as the reference" ,sel_sparse == sel_want ); 1110 }else { 1111report ("the selection boundary gap, in fp32 ulp of the cut" , 1112 (lo - hi ) / (std::fabs (lo )* 1.2e-7 ),"gap/ulp" ); 1113 std::printf (" %-48s last selected %.6f, first rejected %.6f\n" ,"the cut" ,lo ,hi ); 1114 } 1115 } 1116 1117// the pipeline. `--qsa-dense` swaps the SELECTION for every cell and keeps everything else; the sparse 1118// selection above is still compared against the reference either way. 1119 std::vector < int32_t > sel = sel_sparse ; 1120if (dense ) { 1121sel .resize ((size_t )T ); 1122for (int64_t j = 0 ;j < T ;++ j )sel [(size_t )j ]= (int32_t )j ; 1123 } 1124Dev < int32_t > dsel2 ; 1125dsel2 .put (sel ); 1126const int64_t nsel = (int64_t )sel .size (); 1127Dev < uint16_t > dks ((size_t )nsel * NKV * HD ),dvs ((size_t )nsel * NKV * HD ); 1128 strata::kernels::kv_gather (dpk .p ,dpv .p ,dtab .p ,dsel2 .p ,nsel ,Sp ,dks .p ,dvs .p ,nullptr ); 1129Dev < float > dqq ,dattn ((size_t )NH * HD ),dwt ((size_t )NH * nsel ); 1130dqq .put (q ); 1131 strata::kernels::qsa_attend (dqq .p ,dks .p ,dvs .p ,nsel ,S ,dattn .p ,dwt .p ,nullptr ); 1132const std::vector < double > attn = as_d (dattn .get ((size_t )NH * HD )); 1133const std::vector < double > wts = as_d (dwt .get ((size_t )NH * nsel )); 1134 1135const std::vector < double > q64 = as_d (q ); 1136const std::vector < double > attn_f64 = ref_attend (q64 ,NH ,NKV ,HD ,sel ,pc .k ,pc .v ,Alt {},nullptr ); 1137const std::vector < double > attn_f16 = ref_attend (q64 ,NH ,NKV ,HD ,sel ,k16 ,v16 ,Alt {},nullptr ); 1138double num = 0 ,den = 0 ; 1139for (size_t i = 0 ;i < attn .size ();++ i ) { 1140num += std::fabs (attn [i ]- attn_f16 [i ]); 1141den += std::fabs (attn_f16 [i ]); 1142 } 1143report ("qsa_attend vs the reference on the SAME fp16 cache" ,num /den ,"rel" ); 1144 {// the SCALE trap, on data whose softmax is not saturated 1145Alt a ;a .apply_scale = false; 1146const std::vector < double > alt = ref_attend (q64 ,NH ,NKV ,HD ,sel ,k16 ,v16 ,a ,nullptr ); 1147double n2 = 0 ,d2 = 0 ; 1148for (size_t i = 0 ;i < alt .size ();++ i ) { 1149n2 += std::fabs (alt [i ]- attn_f16 [i ]); 1150d2 += std::fabs (attn_f16 [i ]); 1151 } 1152verdict ("omitting 1/sqrt(head_dim) is observable (random fixture)" ,n2 /d2 > 0.05 ,pct (n2 /d2 )); 1153 } 1154if (!(num /den <=1e-5 )) { std::printf (" *** over 1e-5 ***\n" );++ g_bad ; } 1155const double fp16_cost = rel_l1 (attn_f64 ,attn_f16 ); 1156report ("the fp16 KV cache's OWN cost (f32 keys vs fp16 keys)" ,fp16_cost ,"rel" ); 1157if (!(fp16_cost <=1e-3 )) { 1158 std::printf (" *** the phase's 1e-3 for FP16 paths is exceeded by the CACHE ***\n" ); 1159++ g_bad ; 1160 } 1161 { 1162 std::vector < double > w_ref ; 1163ref_attend (q64 ,NH ,NKV ,HD ,sel ,k16 ,v16 ,Alt {},& w_ref ); 1164double wn = 0 ,wd = 0 ; 1165for (int64_t j = 0 ;j < nsel ;++ j ) { 1166wn += std::fabs (wts [(size_t )j ]- w_ref [(size_t )j ]); 1167wd += std::fabs (w_ref [(size_t )j ]); 1168 } 1169report ("the returned weights vs the reference (head 0)" ,wn /wd ,"rel" ); 1170 } 1171 1172// the gate 1173 std::vector < float > q_full ((size_t ) (NH * 2 * HD )); 1174for (auto & x :q_full )x = rnd (2.0 ); 1175Dev < float > dqf ,dattnf ; 1176dqf .put (q_full ); 1177dattnf .put (as_f (attn )); 1178Dev < uint16_t > dgate ((size_t )NH * HD ); 1179 strata::kernels::qsa_gate_apply (dattnf .p ,dqf .p ,S ,dgate .p ,nullptr ); 1180const std::vector < uint16_t > gate16 = dgate .get ((size_t )NH * HD ); 1181const std::vector < double > qf64 = as_d (q_full ); 1182const std::vector < double > gwant = ref_gate (attn ,qf64 ,NH ,HD ,Alt {}); 1183double gnum = 0 ,gden = 0 ; 1184int gbits = 0 ; 1185for (size_t i = 0 ;i < gwant .size ();++ i ) { 1186gnum += std::fabs ((double )f32_from_f16 (gate16 [i ])- gwant [i ]); 1187gden += std::fabs (gwant [i ]); 1188if (gate16 [i ]!= f16_from_f32 ((float )gwant [i ]))++ gbits ; 1189 } 1190report ("qsa_gate_apply vs the double reference" ,gnum /gden ,"rel (f16 out quant ~2.4e-4)" ); 1191if (!(gnum /gden <=1e-3 )) { std::printf (" *** over 1e-3 ***\n" );++ g_bad ; } 1192 std::printf (" %-48s %d of %lld (CUDA's double exp vs libm's, in the last bits)\n" , 1193"fp16 gate bits differing from the reference" ,gbits , (long long )gwant .size ()); 1194 1195auto sep_gate = [& ](const std::string & name ,const Alt & a ) { 1196const std::vector < double > alt = ref_gate (attn ,qf64 ,NH ,HD ,a ); 1197double n2 = 0 ,d2 = 0 ; 1198for (size_t i = 0 ;i < alt .size ();++ i ) { 1199n2 += std::fabs (alt [i ]- gwant [i ]); 1200d2 += std::fabs (gwant [i ]); 1201 } 1202verdict (name ,n2 /d2 > 0.05 ,pct (n2 /d2 )); 1203 }; 1204Alt a10 ;a10 .gate_second_half = false; 1205sep_gate ("the gate from the FIRST half is observable" ,a10 ); 1206Alt a11 ;a11 .gate_sigmoid = false; 1207sep_gate ("silu instead of sigmoid on the QSA gate is observable" ,a11 ); 1208 1209// DENSE vs SPARSE. Below the bound the width IS n_kv, so the two paths must agree EXACTLY (P1.S4's 1210// isolation property, `ref/qsa.py` PROPERTY 9b); above it they must differ, or the switch is a no-op. 1211require ("below the bound, dense and sparse are the SAME selection" , 1212ref_select (sc_want ,2000 ,TOPK , false)== ref_select (sc_want ,2000 ,TOPK , true)); 1213 { 1214// BOTH SIDES COMPUTED HERE, from their own id lists and independently of `--qsa-dense`. The first 1215// version compared against the pipeline's `attn`, which in dense mode IS the dense attention - so the 1216// switch silently turned the check into a comparison of a thing with itself and reported 0.00%. 1217const std::vector < int32_t > dense_all = ref_select (sc_want ,T ,TOPK , true); 1218auto attend_ids = [& ](const std::vector < int32_t >& ids ) { 1219Dev < int32_t > did ; 1220did .put (ids ); 1221Dev < uint16_t > dk2 ((size_t )ids .size ()* NKV * HD ),dv2 ((size_t )ids .size ()* NKV * HD ); 1222 strata::kernels::kv_gather (dpk .p ,dpv .p ,dtab .p ,did .p , (int64_t )ids .size (),Sp ,dk2 .p ,dv2 .p , 1223nullptr ); 1224Dev < float > da ((size_t )NH * HD ); 1225 strata::kernels::qsa_attend (dqq .p ,dk2 .p ,dv2 .p , (int64_t )ids .size (),S ,da .p ,nullptr ,nullptr ); 1226return as_d (da .get ((size_t )NH * HD )); 1227 }; 1228const std::vector < double > dense_attn = attend_ids (dense_all ); 1229const std::vector < double > sparse_attn = attend_ids (sel_sparse ); 1230double dn = 0 ,dd = 0 ; 1231for (size_t i = 0 ;i < sparse_attn .size ();++ i ) { 1232dn += std::fabs (dense_attn [i ]- sparse_attn [i ]); 1233dd += std::fabs (sparse_attn [i ]); 1234 } 1235verdict ("dense differs from sparse at n_kv = 2100 (> 2051)" ,dn /dd > 0.05 ,pct (dn /dd )); 1236 } 1237 } 1238 1239// ================= 7. the empty selection ================= 1240 { 1241Dev < float > dq ((size_t )NH * HD ),dattn ((size_t )NH * HD ); 1242dq .put (std::vector < float > ((size_t )NH * HD ,1.0f )); 1243dattn .put (std::vector < float > ((size_t )NH * HD ,7.0f )); 1244 strata::kernels::qsa_attend (dq .p ,nullptr ,nullptr ,0 ,S ,dattn .p ,nullptr ,nullptr ); 1245const std::vector < float > got = dattn .get ((size_t )NH * HD ); 1246bool allz = true; 1247for (float x :got )if (x != 0.0f )allz = false; 1248require ("an EMPTY selection gives a zero attention, not a NaN" ,allz ,"all 6144 elements zero" ); 1249 } 1250 1251// ================= 8. --bench: what one QSA layer costs at 32K of context ================= 1252if (bench ) { 1253const int64_t T = MAXC ;// 32,768 cells = 32K of context 1254const int64_t nbid = T /R ; 1255const int64_t ps = S .page_size ,n_pages = (T + ps - 1 ) /ps ; 1256const int64_t w = strata::kernels::qsa_selection_width (T ,S ); 1257 std::printf ("\n --bench at n_kv = %lld, page_size %lld, selection width %lld\n" , (long long )T , 1258 (long long )ps , (long long )w ); 1259 std::vector < int32_t > table ((size_t )n_pages ); 1260for (int64_t i = 0 ;i < n_pages ;++ i )table [(size_t )i ]= (int32_t )i ; 1261Dev < int32_t > dtab ; 1262dtab .put (table ); 1263Dev < uint16_t > dpk ((size_t )n_pages * NKV * ps * HD ),dpv ((size_t )n_pages * NKV * ps * HD ); 1264 std::vector < float > kz ((size_t )NKV * HD ),vz ((size_t )NKV * HD ); 1265for (auto & x :kz )x = rnd (1.0 ); 1266for (auto & x :vz )x = rnd (1.0 ); 1267Dev < float > dkz ,dvz ; 1268dkz .put (kz ); 1269dvz .put (vz ); 1270 strata::kernels::kv_append (dpk .p ,dpv .p ,dtab .p ,0 ,dkz .p ,dvz .p ,S ,nullptr ); 1271 1272const size_t ppooled_n = (size_t ) (nbid + 1 )* IDXD ; 1273Dev < float > dpp ((size_t )ppooled_n ),dsc ((size_t )T ); 1274 std::vector < float > pz (ppooled_n ),sz ((size_t )T ); 1275for (auto & x :pz )x = rnd (0.1f ); 1276for (auto & x :sz )x = std::fabs (rnd (1.0f )); 1277dpp .put (pz ); 1278dsc .put (sz ); 1279Dev < float > dqidx ; 1280dqidx .put (q_idx ); 1281Dev < int32_t > dsel ((size_t )w ); 1282Dev < uint16_t > dks ((size_t )w * NKV * HD ),dvs ((size_t )w * NKV * HD ); 1283Dev < float > dq ((size_t )NH * HD ),dattn ((size_t )NH * HD ),dwt ((size_t )NH * w ); 1284 std::vector < float > qv ((size_t )NH * HD ); 1285for (auto & x :qv )x = rnd (1.0 ); 1286dq .put (qv ); 1287 1288auto timeit = [& ](const std::string & name ,int reps , 1289const std::function < void ()> & fn ) { 1290try { 1291 dpct::event_ptr a ,b ; 1292a = new sycl::event (); 1293b = new sycl::event (); 1294fn (); 1295 dpct::get_current_device ().queues_wait_and_throw (); 1296 dpct::sync_barrier (a ); 1297for (int i = 0 ;i < reps ;++ i )fn (); 1298 dpct::sync_barrier (b ); 1299b -> wait_and_throw (); 1300float ms = 0 ; 1301ms = (b -> get_profiling_info < 1302 sycl::info::event_profiling::command_end > ()- 1303a -> get_profiling_info < 1304 sycl::info::event_profiling::command_start > ()) / 13051000000.0f ; 1306 std::printf (" %-48s %8.1f us\n" ,name .c_str (),ms * 1000.0f / (float )reps ); 1307 dpct::destroy_event (a ); 1308 dpct::destroy_event (b ); 1309 } 1310catch (sycl::exception const & exc ) { 1311 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 1312 <<", line:" <<__LINE__ << std::endl ; 1313 std::exit (1 ); 1314 } 1315 }; 1316const int reps = 20 ; 1317timeit ("qsa_index (8193 pooled rows x 4 heads)" ,reps , 1318 [& ] { strata::kernels::qsa_index (dpp .p ,nbid ,dqidx .p ,nullptr ,S ,T ,dsc .p ,nullptr ); }); 1319timeit ("topk_512 (32768 cells)" ,reps , 1320 [& ] { strata::kernels::topk_512 (dsc .p ,T ,S ,w ,dsel .p ,nullptr ); }); 1321 strata::kernels::topk_512 (dsc .p ,T ,S ,w ,dsel .p ,nullptr ); 1322timeit ("kv_gather (2051 ids through the page table)" ,reps , 1323 [& ] { strata::kernels::kv_gather (dpk .p ,dpv .p ,dtab .p ,dsel .p ,w ,S ,dks .p ,dvs .p ,nullptr ); }); 1324timeit ("qsa_attend (2051 selected, 24 heads)" ,reps , 1325 [& ] { strata::kernels::qsa_attend (dq .p ,dks .p ,dvs .p ,w ,S ,dattn .p ,dwt .p ,nullptr ); }); 1326timeit ("kv_append (one cell, 2 heads x 256)" ,200 , 1327 [& ] { strata::kernels::kv_append (dpk .p ,dpv .p ,dtab .p ,0 ,dkz .p ,dvz .p ,S ,nullptr ); }); 1328timeit ("ONE QSA LAYER (index+topk+gather+attend)" ,reps , [& ] { 1329 strata::kernels::qsa_index (dpp .p ,nbid ,dqidx .p ,nullptr ,S ,T ,dsc .p ,nullptr ); 1330 strata::kernels::topk_512 (dsc .p ,T ,S ,w ,dsel .p ,nullptr ); 1331 strata::kernels::kv_gather (dpk .p ,dpv .p ,dtab .p ,dsel .p ,w ,S ,dks .p ,dvs .p ,nullptr ); 1332 strata::kernels::qsa_attend (dq .p ,dks .p ,dvs .p ,w ,S ,dattn .p ,dwt .p ,nullptr ); 1333 }); 1334 } 1335 1336// ================= 6. indexer_key_append IS CAPTURABLE ================= 1337// 1338// THE PROPERTY THE DEVICE-POSITION REFACTOR WAS FOR, TESTED DIRECTLY rather than argued. `indexer_key_append` 1339// took `int64_t pos` as a host scalar, which a CUDA graph bakes in at capture time - so a captured call 1340// would replay the first token's position forever: `slot = pos % r` never advances, no block completes, and 1341// the indexer keeps pooling cells 0-3 for the whole sequence. 1342// 1343// The test captures ONE call, then replays the SAME graph twice with `pos_dev` and `raw` changed between 1344// them, and requires the second replay to land in a DIFFERENT pooled row with the reference's value. If the 1345// position were still baked in, both replays would write row 0 and the pooled rows would be identical. 1346// 1347// That is the negative control built into the assertion: "row 1 is correct" alone could also pass for a 1348// graph that reread the position by accident, but "row 0 unchanged AND row 1 correct AND row 1 != row 0" 1349// cannot pass for a baked-in position. 1350 { 1351 std::printf ("\n-- indexer_key_append under graph capture\n" ); 1352const int R2 = 4 ; 1353const int64_t NCELL = 8 ;// two complete blocks of r=4 1354const size_t IDXD2 = (size_t )IDXD ; 1355 std::vector < float > raw2 ((size_t )NCELL * IDXD2 ); 1356for (size_t i = 0 ;i < raw2 .size ();++ i )raw2 [i ]= (float ) std::sin ((double )i * 0.013 )* 2.0f - 0.3f ; 1357 1358const int64_t nb2 = NCELL /R2 ; 1359Dev < float > pooled2 ((size_t ) (nb2 + 2 )* IDXD2 ),dead2 (IDXD2 ),tail2 ((size_t ) (R2 - 1 )* IDXD2 ); 1360Dev < int32_t > bpos2 (1 ),pos2 (1 ); 1361Dev < float > raw2d (IDXD2 ); 1362 strata::kernels::QsaIndexerBuffers bufs2 {tail2 .p ,dead2 .p ,pooled2 .p ,bpos2 .p }; 1363 1364// capture ONE call, on its own stream 1365 dpct::queue_ptr cs = & dpct::get_in_order_queue (); 1366check (DPCT_CHECK_ERROR ( 1367cs = dpct::get_current_device ().create_queue (true)), 1368"cs" ); 1369check (DPCT_CHECK_ERROR (dpct::experimental::begin_recording (cs )), 1370"begincap" ); 1371 strata::kernels::indexer_key_append (raw2d .p ,pos2 .p ,POS_BASE ,dw_kn .p ,EPS ,bufs2 ,S ,dcos .p ,dsin .p , 1372 (void * )cs ); 1373 dpct::experimental::command_graph_ptr g2 = nullptr ; 1374check (DPCT_CHECK_ERROR (dpct::experimental::end_recording (cs ,& g2 )), 1375"endcap" ); 1376check (DPCT_CHECK_ERROR (dpct::get_current_device ().destroy_queue (cs )), 1377"csd" ); 1378size_t nodes2 = 0 ; 1379check (DPCT_CHECK_ERROR ( 1380 dpct::experimental::get_nodes (g2 ,nullptr ,& nodes2 )), 1381"nodes" ); 1382 dpct::experimental::command_graph_exec_ptr ex2 = nullptr ; 1383check (DPCT_CHECK_ERROR ( 1384ex2 = new sycl::ext::oneapi::experimental::command_graph < 1385 sycl::ext::oneapi::experimental::graph_state::executable > ( 1386g2 -> finalize ())), 1387"inst" ); 1388 1389// replay A: cells 0..3, which completes block 0 1390for (int t = 0 ;t < 4 ;++ t ) { 1391check (DPCT_CHECK_ERROR ( 1392 (dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()) 1393 .memcpy (raw2d .p ,& raw2 [(size_t )t * IDXD2 ],IDXD2 * 4 ) 1394 .wait ()), 1395"r2" ); 1396const int32_t tp = t ; 1397check (DPCT_CHECK_ERROR ( 1398 (dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy (pos2 .p ,& tp ,4 ).wait ()), 1399"p2" ); 1400check (DPCT_CHECK_ERROR (dpct::get_in_order_queue ().ext_oneapi_graph (* ex2 )), 1401"launchA" ); 1402 } 1403const std::vector < float > afterA = pooled2 .get ((size_t ) (nb2 + 2 )* IDXD2 ); 1404 1405// replay B: cells 4..7 through the SAME graph, which completes block 1 1406for (int t = 4 ;t < 8 ;++ t ) { 1407check (DPCT_CHECK_ERROR ( 1408 (dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()) 1409 .memcpy (raw2d .p ,& raw2 [(size_t )t * IDXD2 ],IDXD2 * 4 ) 1410 .wait ()), 1411"r3" ); 1412const int32_t tp = t ; 1413check (DPCT_CHECK_ERROR ( 1414 (dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy (pos2 .p ,& tp ,4 ).wait ()), 1415"p3" ); 1416check (DPCT_CHECK_ERROR (dpct::get_in_order_queue ().ext_oneapi_graph (* ex2 )), 1417"launchB" ); 1418 } 1419check (DPCT_CHECK_ERROR ( 1420 dpct::get_current_device ().queues_wait_and_throw ()), 1421"sync2" ); 1422const std::vector < float > afterB = pooled2 .get ((size_t ) (nb2 + 2 )* IDXD2 ); 1423 1424 std::printf (" %-44s %zu nodes for one call\n" ,"the pooled kernel is capturable" ,nodes2 ); 1425 1426// row 0 must be UNTOUCHED by the second block's replays 1427int row0_same = 0 ; 1428for (size_t d = 0 ;d < IDXD2 ;++ d ) 1429if (afterA [d ]== afterB [d ])++ row0_same ; 1430 std::printf (" %-44s %d of %zu unchanged\n" ,"the first block's row survives replay B" ,row0_same , 1431IDXD2 ); 1432if (row0_same != (int )IDXD2 )++ g_bad ; 1433 1434// row 1 must now be FILLED by the captured graph - the whole point 1435int row1_nonzero = 0 ; 1436for (size_t d = 0 ;d < IDXD2 ;++ d ) 1437if (afterB [IDXD2 + d ]!= 0.0f )++ row1_nonzero ; 1438 std::printf (" %-44s %d of %zu non-zero\n" ,"the SECOND block's row arrives through the same graph" , 1439row1_nonzero ,IDXD2 ); 1440if (row1_nonzero != (int )IDXD2 )++ g_bad ; 1441 1442// and the two rows must DIFFER, which a baked-in position cannot produce 1443int rows_differ = 0 ; 1444for (size_t d = 0 ;d < IDXD2 ;++ d ) 1445if (afterB [d ]!= afterB [IDXD2 + d ])++ rows_differ ; 1446 std::printf (" %-44s %d of %zu differ\n" ,"the two pooled rows are different keys" ,rows_differ , 1447IDXD2 ); 1448// A baked-in position would have written row 0 a second time and left row 1 at zero, so these two 1449// assertions together are the negative control for the refactor. 1450if (rows_differ != (int )IDXD2 )++ g_bad ; 1451 1452check (DPCT_CHECK_ERROR (delete (ex2 )),"exd" ); 1453check (DPCT_CHECK_ERROR (delete (g2 )),"gd" ); 1454 } 1455 1456// ================= the NATIVE indexer's batched append vs the sequential one ================= 1457// The prefill path appends a chunk in one native_qsa_indexer_append_batch call, the decode path appends 1458// token by token - and one cache must never be able to tell which path filled it (rope_scaling.hpp's 1459// one-rotation rule). So the batch's whole end state must be BIT-IDENTICAL to the sequential appends', 1460// under all three scaling configs: none (today's rotation), linear 2 (pure angle shrink, no correction) 1461// and yarn 2 (corr-dims ramp and the mscale magnitude) - both kernels must take the same RopeScaling. 1462// "Bit-identical" is asserted on the bit representations (memcmp of the state words): float != would 1463// pass a NaN-payload or -0.0 flip that the claim does not cover. Eight cells: exactly two completed 1464// blocks, so the paths' end states agree on block_pos too (a mid-block chunk end leaves the sequential 1465// path pointing at the open block's base and the batch at the last completed one's - upstream C-2's own 1466// semantics, the same for every scaling; see native_qsa_indexer.hpp's block_pos contract). 1467 { 1468 std::printf ("\n-- the native indexer's batched append vs the sequential one\n" ); 1469const int64_t NB = 8 ;// exactly two complete blocks of r=4 1470const int32_t BASE = 100 ;// positions 100..107, not cell indices 0..7 1471const int64_t MC = 1024 ;// the capacity both sides validate against 1472using RST = strata::kernels::RopeScalingType ; 1473struct Variant {const char * name ;RST type ;double factor ;double ext ; }; 1474const Variant variants []= {{"none" ,RST ::None ,1.0 ,0.0 }, 1475 {"linear 2" ,RST ::Linear ,2.0 ,0.0 }, 1476 {"yarn 2" ,RST ::YaRN ,2.0 ,1.0 }}; 1477 std::vector < float > raws ((size_t )NB * IDXD ); 1478for (int64_t t = 0 ;t < NB ;++ t ) 1479for (int64_t d = 0 ;d < IDXD ;++ d ) 1480raws [(size_t )t * IDXD + d ]= (float ) (gauss (rng )* std::pow (4.0 , (double ) (t %4 ))); 1481 dpct::queue_ptr cs = & dpct::get_in_order_queue (); 1482check (DPCT_CHECK_ERROR ( 1483cs = dpct::get_current_device ().create_queue (true)), 1484"cs" ); 1485 std::vector < float > none_pooled ; 1486for (const Variant & var :variants ) { 1487 strata::kernels::RopeScaling sc ; 1488sc .type = var .type ; 1489sc .factor = var .factor ; 1490sc .ext_factor = var .ext ; 1491const size_t prows = (size_t ) (MC /R + 1 )* IDXD ,trows = (size_t ) (R - 1 )* IDXD ; 1492Dev < float > pooledA (prows ),deadA (IDXD ),tailA (trows ),pooledB (prows ),deadB (IDXD ),tailB (trows ); 1493Dev < int32_t > bposA (1 ),bposB (1 ),dpos (1 ); 1494for (Dev < float >* dp : {& pooledA ,& deadA ,& tailA ,& pooledB ,& deadB ,& tailB }) 1495check ( 1496DPCT_CHECK_ERROR ( 1497 (dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()) 1498 .memset (dp -> p ,0 , 1499dp == & pooledA || dp == & pooledB ?prows * 4 1500 :dp == & deadA || dp == & deadB ?IDXD * 4 1501 :trows * 4 ) 1502 .wait ()), 1503"zero" ); 1504check (DPCT_CHECK_ERROR ( 1505 (dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memset (bposA .p ,0 ,4 ).wait ()), 1506"zero" ); 1507check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()) 1508 .memset (bposB .p ,0 ,4 ) 1509 .wait ()), 1510"zero" ); 1511Dev < float > draw ((size_t )IDXD ),drawAll ; 1512drawAll .put (raws ); 1513 strata::kernels::QsaIndexerBuffers bufsA {tailA .p ,deadA .p ,pooledA .p ,bposA .p }; 1514 strata::kernels::QsaIndexerBuffers bufsB {tailB .p ,deadB .p ,pooledB .p ,bposB .p }; 1515for (int64_t t = 0 ;t < NB ;++ t ) {// the sequential side: one cell, its device position 1516check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()) 1517 .memcpy (draw .p , 1518& raws [(size_t )t * IDXD ], 1519 (size_t )IDXD * 4 ) 1520 .wait ()), 1521"raw" ); 1522const int32_t tp = (int32_t )t ; 1523check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()) 1524 .memcpy (dpos .p ,& tp ,4 ) 1525 .wait ()), 1526"pos" ); 1527 strata::kernels::native_qsa_indexer_append (draw .p ,dpos .p ,BASE ,dw_kn .p ,EPS ,bufsA ,S ,MC ,sc ,cs ); 1528// SYCL port: cudaMemcpy on the legacy stream waited for this append before the next copy refilled 1529// `draw`; a default-queue copy does not wait for work on `cs`, so without this the next cell's raw 1530// keys could overwrite this one before the kernel reads them 1531check (DPCT_CHECK_ERROR (cs -> wait ()),"append" ); 1532 } 1533 strata::kernels::native_qsa_indexer_append_batch (drawAll .p ,NB ,0 ,BASE ,dw_kn .p ,EPS ,bufsB ,S ,MC ,sc ,cs ); 1534// #783 PR-d: native_qsa_indexer_append_steps - the verify window's n cells in one launch (positions at a 1535// stride: kStepCount in a window, 1 in the commit graph) - leaves the same buffers as the sequential calls 1536for (const int stride : {1 ,5 }) { 1537Dev < float > pooledC (prows ),deadC (IDXD ),tailC (trows ); 1538Dev < int32_t > bposC (1 ),dposC ((size_t )NB * stride ); 1539check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()) 1540 .memset (pooledC .p ,0 ,prows * 4 ) 1541 .wait ()), 1542"zero" ); 1543check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()) 1544 .memset (deadC .p ,0 ,IDXD * 4 ) 1545 .wait ()), 1546"zero" ); 1547check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()) 1548 .memset (tailC .p ,0 ,trows * 4 ) 1549 .wait ()), 1550"zero" ); 1551check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()) 1552 .memset (bposC .p ,0 ,4 ) 1553 .wait ()), 1554"zero" ); 1555 std::vector < int32_t > hp ((size_t )NB * stride ,-1 ); 1556for (int64_t t = 0 ;t < NB ;++ t )hp [(size_t )t * stride ]= (int32_t )t ; 1557/* 1558DPCT1114: cudaMemcpy is migrated to asynchronization 1559memcpy, assuming in the original code the source host memory is 1560pageable memory. If the memory is not pageable, call wait() on 1561event return by memcpy API to ensure synchronization behavior. 1562*/ 1563check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy ( 1564dposC .p ,hp .data (),hp .size ()* 4 ).wait ()), 1565"pos" ); 1566 strata::kernels::QsaIndexerBuffers bufsC {tailC .p ,deadC .p ,pooledC .p ,bposC .p }; 1567 strata::kernels::native_qsa_indexer_append_steps (drawAll .p ,dposC .p ,stride , (int )NB ,BASE ,dw_kn .p ,EPS , 1568bufsC ,S ,MC ,sc ,cs ); 1569check (DPCT_CHECK_ERROR (cs -> wait ()),"sync" ); 1570const std::vector < float > pc = pooledC .get (prows ),dc = deadC .get ((size_t )IDXD ),tc = tailC .get (trows ); 1571const std::vector < int32_t > bc = bposC .get (1 ); 1572const std::vector < float > pa2 = pooledA .get (prows ),da2 = deadA .get ((size_t )IDXD ),ta2 = tailA .get (trows ); 1573const std::vector < int32_t > ba2 = bposA .get (1 ); 1574const bool same = std::memcmp (pc .data (),pa2 .data (),pc .size ()* 4 )== 0 && 1575 std::memcmp (dc .data (),da2 .data (),dc .size ()* 4 )== 0 && 1576 std::memcmp (tc .data (),ta2 .data (),tc .size ()* 4 )== 0 && bc [0 ]== ba2 [0 ]; 1577 std::printf (" %-44s %s\n" , (std::string ("append_steps (stride " )+ std::to_string (stride )+ ") vs sequential, " + var .name ).c_str (), 1578same ?"bit-identical" :"*** WRONG ***" ); 1579if (!same )++ g_bad ; 1580 } 1581check (DPCT_CHECK_ERROR (cs -> wait ()),"sync" ); 1582const std::vector < float > pa = pooledA .get (prows ),pb = pooledB .get (prows ); 1583const std::vector < float > da = deadA .get ((size_t )IDXD ),db = deadB .get ((size_t )IDXD ); 1584const std::vector < float > ta = tailA .get (trows ),tbb = tailB .get (trows ); 1585const std::vector < int32_t > ba = bposA .get (1 ),bb = bposB .get (1 ); 1586long long bad = 0 ; 1587for (size_t i = 0 ;i < pa .size ();++ i )bad += std::memcmp (& pa [i ],& pb [i ],4 )!= 0 ; 1588for (size_t i = 0 ;i < da .size ();++ i )bad += std::memcmp (& da [i ],& db [i ],4 )!= 0 ; 1589for (size_t i = 0 ;i < ta .size ();++ i )bad += std::memcmp (& ta [i ],& tbb [i ],4 )!= 0 ; 1590bad += std::memcmp (& ba [0 ],& bb [0 ],4 )!= 0 ; 1591 std::printf (" %-44s %s (%lld of %zu state words differ)\n" , 1592 (std::string ("batch vs sequential, " )+ var .name ).c_str (), 1593bad ?"*** WRONG ***" :"bit-identical" ,bad ,pa .size ()+ da .size ()+ ta .size ()+ 1 ); 1594if (bad )++ g_bad ; 1595if (var .type == RST ::None )none_pooled = pa ; 1596else { 1597int moved = 0 ; 1598for (size_t i = 0 ;i < pa .size ();++ i )moved += std::memcmp (& pa [i ],& none_pooled [i ],4 )!= 0 ; 1599 std::printf (" %-44s %d of %zu pooled words differ from the none baseline\n" , 1600 (std::string ("the scaling is visible, " )+ var .name ).c_str (),moved ,pa .size ()); 1601if (!moved ) { std::printf (" *** the batched append ignored its scaling ***\n" );++ g_bad ; } 1602 } 1603 } 1604check (DPCT_CHECK_ERROR (dpct::get_current_device ().destroy_queue (cs )), 1605"csd" ); 1606 } 1607 1608// ================= the spare (position 0) under rope scaling: the table indexer vs the native one ========= 1609// The spare key (`dead`, and `pooled[0]` until the first block completes) rotates at angle 0. Its sine is 1610// 0 in every scaling, so the rotation is `v * cos_tab[0][pair]`: exactly `v` unscaled (row 0 is (1, 0), the 1611// bit-exact value section 2 asserts), `v * mscale` under YaRN - the magnitude every other pooled row and 1612// the native kernel's spare carry. The table kernel used to skip the rotation at position 0, which left 1613// the spare the one unscaled key of a scaled cache. Asserted per variant: the table spare is BIT-EXACTLY 1614// the unscaled spare times row 0 on the rotated dims and the unscaled spare past them; `pooled[0]` equals 1615// `dead`; the native spare carries the same factor (to f32 rounding: its mscale is formed in float); and 1616// under YaRN the factor is observable (row 0 is not 1). 1617 { 1618 std::printf ("\n-- the spare key (position 0) under rope scaling: table indexer vs native indexer\n" ); 1619using RST = strata::kernels::RopeScalingType ; 1620struct Variant {const char * name ;RST type ;double factor ;double ext ; }; 1621const Variant variants []= {{"none" ,RST ::None ,1.0 ,0.0 }, 1622 {"linear 2" ,RST ::Linear ,2.0 ,0.0 }, 1623 {"yarn 2" ,RST ::YaRN ,2.0 ,1.0 }}; 1624const int64_t MC = 64 ,HALF = S .n_rot /2 ,NROT = S .n_rot ; 1625 std::vector < float > raw0 ((size_t )IDXD ); 1626for (int64_t d = 0 ;d < IDXD ;++ d )raw0 [(size_t )d ]= rnd (3.0 ); 1627Dev < float > draw0 ; 1628draw0 .put (raw0 ); 1629Dev < int32_t > dpos0 (1 ); 1630const int32_t zero = 0 ; 1631check (DPCT_CHECK_ERROR ( 1632 (dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy (dpos0 .p ,& zero ,4 ).wait ()), 1633"pos0" ); 1634 dpct::queue_ptr cs = & dpct::get_in_order_queue (); 1635check (DPCT_CHECK_ERROR ( 1636cs = dpct::get_current_device ().create_queue (true)), 1637"cs" ); 1638const size_t prows = (size_t ) (MC /R + 1 )* IDXD ,trows = (size_t ) (R - 1 )* IDXD ; 1639// one cell at position 0 through either kernel; returns (dead, pooled[0]) 1640auto spare = [& ](bool native ,const strata::kernels::RopeScaling & sc , 1641 std::vector < float > & dead , 1642 std::vector < float > & pooled0 ) { 1643try { 1644Dev < float > pooled (prows ),dd ((size_t )IDXD ),tail (trows ); 1645Dev < int32_t > bpos (1 ); 1646check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()) 1647 .memset (pooled .p ,0 ,prows * 4 ) 1648 .wait ()), 1649"zero" ); 1650check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()) 1651 .memset (dd .p ,0 , (size_t )IDXD * 4 ) 1652 .wait ()), 1653"zero" ); 1654check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()) 1655 .memset (tail .p ,0 ,trows * 4 ) 1656 .wait ()), 1657"zero" ); 1658check (DPCT_CHECK_ERROR ( 1659 (dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memset (bpos .p ,0 ,4 ).wait ()), 1660"zero" ); 1661 strata::kernels::QsaIndexerBuffers bufs {tail .p ,dd .p ,pooled .p ,bpos .p }; 1662if (native ) { 1663 strata::kernels::native_qsa_indexer_append (draw0 .p ,dpos0 .p ,0 ,dw_kn .p ,EPS ,bufs ,S ,MC ,sc ,cs ); 1664 }else { 1665 std::vector < float > tc ((size_t ) (MC * HALF )),ts (tc .size ()); 1666 strata::kernels::build_rope_table ((int )NROT ,sc , (int )MC ,tc .data (),ts .data ()); 1667Dev < float > dc ,dsn ; 1668dc .put (tc ); 1669dsn .put (ts ); 1670 strata::kernels::indexer_key_append (draw0 .p ,dpos0 .p ,0 ,dw_kn .p ,EPS ,bufs ,S ,dc .p ,dsn .p ,cs ); 1671 } 1672check (DPCT_CHECK_ERROR (cs -> wait ()),"sync" ); 1673dead = dd .get ((size_t )IDXD ); 1674pooled0 = pooled .get ((size_t )IDXD ); 1675 } 1676catch (sycl::exception const & exc ) { 1677 std::cerr <<exc .what () 1678 <<"Exception caught at file:" <<__FILE__ 1679 <<", line:" <<__LINE__ << std::endl ; 1680 std::exit (1 ); 1681 } 1682 }; 1683 std::vector < float > t_none ,t_none_p ,n_none ,n_none_p ; 1684for (const Variant & var :variants ) { 1685 strata::kernels::RopeScaling sc ; 1686sc .type = var .type ; 1687sc .factor = var .factor ; 1688sc .ext_factor = var .ext ; 1689 std::vector < float > row0c ((size_t ) (MC * HALF )),row0s (row0c .size ()); 1690 strata::kernels::build_rope_table ((int )NROT ,sc , (int )MC ,row0c .data (),row0s .data ()); 1691 std::vector < float > td ,tp ,nd ,np ; 1692spare (false,sc ,td ,tp ); 1693spare (true,sc ,nd ,np ); 1694if (var .type == RST ::None ) {t_none = td ;t_none_p = tp ;n_none = nd ;n_none_p = np ; } 1695long long tbad = 0 ,pbad = 0 ,sin_bad = 0 ; 1696double nworst = 0 ; 1697for (int64_t i = 0 ;i < HALF ;++ i )sin_bad += row0s [(size_t )i ]!= 0.0f ; 1698for (int64_t d = 0 ;d < IDXD ;++ d ) { 1699const float c0 = d < NROT ?row0c [(size_t ) (d %HALF )] :1.0f ; 1700const float want = d < NROT ?t_none [(size_t )d ]* c0 :t_none [(size_t )d ]; 1701tbad += std::memcmp (& td [(size_t )d ],& want ,4 )!= 0 ; 1702pbad += std::memcmp (& tp [(size_t )d ],& td [(size_t )d ],4 )!= 0 ; 1703const double nwant = (double )n_none [(size_t )d ]* (double )c0 ; 1704const double den = std::max (std::fabs (nwant ),1e-6 ); 1705nworst = std::max (nworst , std::fabs ((double )nd [(size_t )d ]- nwant ) /den ); 1706 } 1707require (std::string (" " )+ var .name + ": row 0 of the table is (c, 0)" ,sin_bad == 0 , 1708 std::to_string (sin_bad )+ " nonzero sines" ); 1709require (std::string (" " )+ var .name + ": the table spare is the unscaled spare times row 0, BIT-EXACT" , 1710tbad == 0 , std::to_string (tbad )+ " of " + std::to_string (IDXD )+ " wrong" ); 1711require (std::string (" " )+ var .name + ": the table's pooled[0] is its spare" ,pbad == 0 , 1712 std::to_string (pbad )+ " wrong" ); 1713require (std::string (" " )+ var .name + ": the native spare carries the same row-0 factor" ,nworst <=4e-7 , 1714"worst relative " + std::to_string (nworst )); 1715if (var .type == RST ::YaRN ) { 1716int moved = 0 ; 1717for (int64_t d = 0 ;d < NROT ;++ d )moved += std::memcmp (& td [(size_t )d ],& t_none [(size_t )d ],4 )!= 0 ; 1718require (" yarn 2: the magnitude correction is observable on the table spare" , 1719row0c [0 ]!= 1.0f && moved > NROT /2 , 1720"row0 cos " + std::to_string (row0c [0 ])+ ", " + std::to_string (moved )+ " dims moved" ); 1721 } 1722 } 1723check (DPCT_CHECK_ERROR (dpct::get_current_device ().destroy_queue (cs )), 1724"csd" ); 1725 } 1726 1727 std::printf ("\nqsa: %d failures\n" ,g_bad ); 1728if (g_bad )return 1 ; 1729if (selftest ) std::printf ("qsa_parity OK\n" ); 1730return 0 ; 1731}