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