okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
5af104b51
main
1// src/kernels/rope_parity.cpp - P2.S2's parity test for NEOX partial RoPE. 2// 3// TWO CHECKS, deliberately separated so each can be tight: 4// 5// 1. THE TABLE against the float64 reference - `theta ** (-2i/n_rot)`, `pos * inv`, `cos`/`sin`, all in 6// double exactly as `ref/qsa.py::rope_freqs` does. Compared as float32 after the cast, so a mismatch 7// here is a real arithmetic difference and not a formatting one. 8// 2. THE ROTATION against a host rotation written from `ref/qsa.py::rope_neox`, using the SAME table the 9// kernel is given. Both sides then perform identical float32 operations, so this is BIT-EXACT - and a 10// bit-exact rotation plus a table that matches the reference means the composition matches too. 11// 12// A single end-to-end comparison would have had to carry one loose tolerance for both, and the interesting 13// failure - the NEOX pairing being wrong - is a PERMUTATION that a loose tolerance over all 256 dims would 14// happily accept. 15// 16// Check 4 extends the same discipline to the SCALED tables (rope scaling: none/linear/YaRN). The rotation 17// kernel cannot see scaling - it lives in the table contents - so each variant's TABLE is held to a float64 18// transcription of ggml's `rope_yarn` spec (the ramp helper is shared, the `rope_neox_pair` convention), and 19// the two properties a tolerance could never fake get their own structural checks: at position 0 every pair's 20// angle is 0, so YaRN's mscale stands naked in cos_tab[0], and at a far position the first pair must match 21// EXTRAPOLATION while the last matches INTERPOLATION. An observability assertion closes it: if the scaled 22// and unscaled tables were indistinguishable, every green number above would be vacuous. 23// 24// Check 5 holds the TWO PATHS together: the table path's float64 host trig and the native path's float32 25// fast-math device trig must answer to the same `RopeScaling`, yarn and none alike, so one cache never 26// mixes two rotations. 27#define DPCT_PROFILING_ENABLED 28#include <sycl/sycl.hpp> 29#include <dpct/dpct.hpp> 30#include "strata/kernels/rope.hpp" 31#include "strata/kernels/native_qsa.hpp" 32#include "strata/kernels/native_rope.hpp" 33 34#include <cmath> 35#include <cstdio> 36#include <cstdlib> 37#include <cstring> 38#include <random> 39#include <string> 40#include <vector> 41 42namespace { 43 44void check (dpct::err0 e ,const char * what ) { 45} 46 47}// namespace 48 49int main (int argc ,char ** argv ) { 50bool selftest = false; 51for (int i = 1 ;i < argc ;++ i ) { 52if (std::string (argv [i ])== "--selftest" )selftest = true; 53else { std::fprintf (stderr ,"usage: rope_parity [--selftest]\n" );return 2 ; } 54 } 55 56const int n_rot = 64 ;// the artifact's rope.dimension_count 57const double theta = 1.0e7 ;// rope.freq_base 58const int head_dim = 256 ; 59const int rows = 24 * 8 ;// 24 heads over 8 positions, so several positions exercise the table 60const int max_pos = 32 ; 61const int half = n_rot /2 ; 62int bad = 0 ; 63 64// ---- 1. the table against the float64 reference 65 std::vector < float > hcos ((size_t )max_pos * half ),hsin ((size_t )max_pos * half ); 66 strata::kernels::build_rope_table (n_rot ,theta ,max_pos ,hcos .data (),hsin .data ()); 67long long table_bad = 0 ; 68double table_worst = 0.0 ; 69for (int p = 0 ;p < max_pos ;++ p ) { 70for (int i = 0 ;i < half ;++ i ) { 71const double inv = std::pow (theta ,-2.0 * (double )i / (double )n_rot ); 72const double ang = (double )p * inv ; 73const float rc = (float ) std::cos (ang ),rs = (float ) std::sin (ang ); 74if (std::memcmp (& rc ,& hcos [(size_t )p * half + i ],4 )!= 0 )++ table_bad ; 75if (std::memcmp (& rs ,& hsin [(size_t )p * half + i ],4 )!= 0 )++ table_bad ; 76table_worst = std::max (table_worst , 77 std::fabs ((double )rc - (double )hcos [(size_t )p * half + i ])); 78 } 79 } 80 std::printf (" rope table vs float64 reference %s (%lld of %d entries differ, worst %.1e)\n" , 81table_bad ?"*** WRONG ***" :"bit-exact" ,table_bad ,max_pos * half * 2 ,table_worst ); 82bad += (int )table_bad ; 83 84// ---- 2. the rotation, against the same spec in float32 with the SAME table 85 std::mt19937 rng (11 ); 86 std::normal_distribution < float > gauss (0.0f ,1.0f ); 87 std::vector < float > x ((size_t )rows * head_dim ); 88for (auto & v :x )v = gauss (rng ); 89 std::vector < int > pos ((size_t )rows ); 90for (int r = 0 ;r < rows ;++ r )pos [(size_t )r ]= r %max_pos ; 91 92 std::vector < float > ref (x .size ()); 93for (int r = 0 ;r < rows ;++ r ) { 94const float * xr = & x [(size_t )r * head_dim ]; 95float * orow = & ref [(size_t )r * head_dim ]; 96for (int d = 0 ;d < head_dim ;++ d )orow [d ]= xr [d ];// the tail passes through 97for (int i = 0 ;i < half ;++ i ) { 98const float c = hcos [(size_t )pos [(size_t )r ]* half + i ]; 99const float s = hsin [(size_t )pos [(size_t )r ]* half + i ]; 100const float a = xr [i ],b = xr [half + i ]; 101orow [i ]= a * c - b * s ; 102orow [half + i ]= a * s + b * c ; 103 } 104 } 105 106float * d_x = nullptr ,* d_out = nullptr ,* d_cos = nullptr ,* d_sin = nullptr ; 107int * d_pos = nullptr ; 108check (DPCT_CHECK_ERROR (d_x = sycl::malloc_device < float > ( 109x .size (), dpct::get_in_order_queue ())), 110"malloc x" ); 111check (DPCT_CHECK_ERROR (d_out = sycl::malloc_device < float > ( 112ref .size (), dpct::get_in_order_queue ())), 113"malloc out" ); 114check (DPCT_CHECK_ERROR (d_cos = sycl::malloc_device < float > ( 115hcos .size (), dpct::get_in_order_queue ())), 116"malloc cos" ); 117check (DPCT_CHECK_ERROR (d_sin = sycl::malloc_device < float > ( 118hsin .size (), dpct::get_in_order_queue ())), 119"malloc sin" ); 120check (DPCT_CHECK_ERROR (d_pos = sycl::malloc_device < int > ( 121pos .size (), dpct::get_in_order_queue ())), 122"malloc pos" ); 123/* 124DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming 125in the original code the source host memory is pageable memory. If the 126memory is not pageable, call wait() on event return by memcpy API to ensure 127synchronization behavior. 128*/ 129check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy ( 130d_x ,x .data (),x .size ()* sizeof (float )).wait ()), 131"copy x" ); 132/* 133DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming 134in the original code the source host memory is pageable memory. If the 135memory is not pageable, call wait() on event return by memcpy API to ensure 136synchronization behavior. 137*/ 138check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy ( 139d_cos ,hcos .data (),hcos .size ()* sizeof (float )).wait ()), 140"copy cos" ); 141/* 142DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming 143in the original code the source host memory is pageable memory. If the 144memory is not pageable, call wait() on event return by memcpy API to ensure 145synchronization behavior. 146*/ 147check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy ( 148d_sin ,hsin .data (),hsin .size ()* sizeof (float )).wait ()), 149"copy sin" ); 150/* 151DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming 152in the original code the source host memory is pageable memory. If the 153memory is not pageable, call wait() on event return by memcpy API to ensure 154synchronization behavior. 155*/ 156check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy ( 157d_pos ,pos .data (),pos .size ()* sizeof (int )).wait ()), 158"copy pos" ); 159 strata::kernels::rope_neox_apply (d_x ,d_out ,rows ,head_dim ,n_rot ,d_cos ,d_sin ,d_pos ,nullptr ); 160 std::vector < float > got (ref .size ()); 161check (DPCT_CHECK_ERROR ( 162 (dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()) 163 .memcpy (got .data (),d_out ,got .size ()* sizeof (float )) 164 .wait ()), 165"back" ); 166 167// A RELATIVE TOLERANCE, NOT BIT EQUALITY. *c - b*s is one of the expressions the compiler is free to 168// contract into an FMA, and the host and device compilers choose differently - so a handful of values 169// differ in the last bit. Round 167 established this the hard way: a bit-equality expectation that a 170// kernel cannot meet is a test that reports a correct kernel as broken. The residual is reported, and if 171// it were structural (a wrong pairing, a wrong table entry) it would be O(1), not O(1 ULP). 172long long rot_bad = 0 ; 173double worst = 0.0 ; 174long long first_bad = -1 ; 175// The denominator is the ROW'S INPUT MAGNITUDE, not the element's own value. *c - b*s cancels, so an 176// element whose result is near zero reports a large relative error for a 1-ULP absolute one - which is the 177// same metric mistake round 169 found on Q4_K's dot products, where the fix was to measure against 178// sum|term| instead of the result. Here the natural scale of the computation is the largest input in the 179// row, because every output element is a combination of two inputs with |cos|,|sin| <= 1. 180 std::vector < double > row_scale ((size_t )rows ,0.0 ); 181for (int r = 0 ;r < rows ;++ r ) { 182double m = 0 ; 183for (int d = 0 ;d < head_dim ;++ d )m = std::max (m , (double ) std::fabs (x [(size_t )r * head_dim + d ])); 184row_scale [(size_t )r ]= m > 1e-30 ?m :1e-30 ; 185 } 186for (size_t i = 0 ;i < ref .size ();++ i ) { 187const double a = ref [i ],b = got [i ]; 188const double rel = std::fabs (a - b ) /row_scale [i / (size_t )head_dim ]; 189if (!(rel <=worst ))worst = rel ; 190if (!(rel <=1e-6 )) {if (first_bad < 0 )first_bad = (long long )i ;++ rot_bad ; } 191 } 192 std::printf (" rope rotation vs host reference %s (%lld of %zu over 1e-6, worst rel %.3e)\n" , 193rot_bad ?"*** WRONG ***" :"agrees" ,rot_bad ,ref .size (),worst ); 194if (first_bad >=0 ) std::printf (" first over-tolerance at element %lld\n" ,first_bad ); 195bad += (int )rot_bad ; 196 197// ---- 3. THE PAIRING, asserted structurally rather than as a tolerance. NEOX pairs (i, i+half); the 198// adjacent-pair convention would pair (2i, 2i+1). Feed an input that is 1 at dim 0 and 0 elsewhere, and 199// check WHICH dims move: under NEOX only dims 0 and half may change, under the adjacent convention only 200// dims 0 and 1 may. A tolerance over all 256 dims cannot tell the two apart. 201 { 202 std::vector < float > e ((size_t )head_dim ,0.0f ); 203e [0 ]= 1.0f ; 204 std::vector < float > o ((size_t )head_dim ,0.0f ); 205/* 206DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, 207assuming in the original code the source host memory is pageable memory. 208If the memory is not pageable, call wait() on event return by memcpy API 209to ensure synchronization behavior. 210*/ 211check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy ( 212d_x ,e .data (),e .size ()* sizeof (float )).wait ()), 213"copy e" ); 214// position 7, NOT position 0: at pos 0 sin is exactly 0, so dim half legitimately does not move and 215// the check would report the correct kernel as wrong. The first version made exactly that mistake. 216int p7 = 7 ; 217check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()) 218 .memcpy (d_pos ,& p7 ,sizeof (int )) 219 .wait ()), 220"copy p7" ); 221 strata::kernels::rope_neox_apply (d_x ,d_out ,1 ,head_dim ,n_rot ,d_cos ,d_sin ,d_pos ,nullptr ); 222check (DPCT_CHECK_ERROR ( 223 (dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()) 224 .memcpy (o .data (),d_out ,o .size ()* sizeof (float )) 225 .wait ()), 226"back e" ); 227int moved [4 ]= {0 ,0 ,0 ,0 };// dims 0, 1, half, half+1 228const float * chk [4 ]= {& e [0 ],& e [1 ],& e [half ],& e [half + 1 ]}; 229 (void )chk ; 230moved [0 ]= (o [0 ]!= 0.0f || o [half ]!= 0.0f ) ?1 :0 ; 231const bool adjacent_moved = (o [1 ]!= 0.0f ); 232const bool neox_moved = (o [half ]!= 0.0f ); 233 std::printf (" pairing: dim 0 set -> NEOX moves dim %d (o[half]=%.6f), adjacent would move dim 1 " 234"(o[1]=%.6f) %s\n" ,half , (double )o [half ], (double )o [1 ], 235 (neox_moved && !adjacent_moved ) ?"NEOX confirmed" :"*** WRONG CONVENTION ***" ); 236if (!(neox_moved && !adjacent_moved ))++ bad ; 237 } 238 239// ---- 4. THE SCALED TABLES (rope_scaling.hpp). Scaling lives in the table contents, so each variant is 240// a table check: a float64 transcription of the ggml spec, bit-exact after the float32 cast, plus the 241// structural and observability checks the tolerances cannot cover. 242 { 243// 4a. type None IS the five-argument builder above - bit for bit. 244 std::vector < float > nc ((size_t )max_pos * half ),ns ((size_t )max_pos * half ); 245 strata::kernels::RopeScaling none ; 246none .freq_base = theta ; 247 strata::kernels::build_rope_table (n_rot ,none ,max_pos ,nc .data (),ns .data ()); 248const long long none_bad = 249 (long long ) (std::memcmp (nc .data (),hcos .data (),nc .size ()* 4 )!= 0 )+ 250 (long long ) (std::memcmp (ns .data (),hsin .data (),ns .size ()* 4 )!= 0 ); 251 std::printf (" scaled table, None vs unscaled builder %s\n" ,none_bad ?"*** WRONG ***" :"bit-identical" ); 252bad += (int )none_bad ; 253 254// 4b. LINEAR, factor 4: `ang = p * inv / 4` in float64. The factor is a power of two on purpose - 255// dividing by it is exact, so no multiplication-order rounding can sneak between spec and builder. 256 strata::kernels::RopeScaling lin ; 257lin .type = strata::kernels::RopeScalingType ::Linear ; 258lin .freq_base = theta ; 259lin .factor = 4.0 ; 260 std::vector < float > lc ((size_t )max_pos * half ),ls ((size_t )max_pos * half ); 261 strata::kernels::build_rope_table (n_rot ,lin ,max_pos ,lc .data (),ls .data ()); 262long long lin_bad = 0 ; 263for (int p = 0 ;p < max_pos ;++ p ) { 264for (int i = 0 ;i < half ;++ i ) { 265const double inv = std::pow (theta ,-2.0 * (double )i / (double )n_rot ); 266const double ang = (double )p * inv /4.0 ; 267const float rc = (float ) std::cos (ang ),rs = (float ) std::sin (ang ); 268if (std::memcmp (& rc ,& lc [(size_t )p * half + i ],4 )!= 0 )++ lin_bad ; 269if (std::memcmp (& rs ,& ls [(size_t )p * half + i ],4 )!= 0 )++ lin_bad ; 270 } 271 } 272 std::printf (" scaled table, linear factor 4 %s (%lld of %d entries differ)\n" , 273lin_bad ?"*** WRONG ***" :"bit-exact" ,lin_bad ,max_pos * half * 2 ); 274bad += (int )lin_bad ; 275 276// 4c. THE INTERPOLATION CLAIM ITSELF: linear(4) at position p is `none` at p/4 - the same table row, 277// bit for bit, at every position divisible by the factor. 278 std::vector < float > wc ((size_t )4 * max_pos * half ),ws ((size_t )4 * max_pos * half ); 279 strata::kernels::build_rope_table (n_rot ,lin ,4 * max_pos ,wc .data (),ws .data ()); 280long long equiv_bad = 0 ; 281for (int p = 0 ;p < 4 * max_pos ;p += 4 ) { 282for (int i = 0 ;i < half ;++ i ) { 283if (std::memcmp (& wc [(size_t )p * half + i ],& hcos [(size_t ) (p /4 )* half + i ],4 )!= 0 )++ equiv_bad ; 284if (std::memcmp (& ws [(size_t )p * half + i ],& hsin [(size_t ) (p /4 )* half + i ],4 )!= 0 )++ equiv_bad ; 285 } 286 } 287 std::printf (" linear(4) @ p == none @ p/4 %s (%lld of %d rows differ)\n" , 288equiv_bad ?"*** WRONG ***" :"bit-identical" ,equiv_bad ,max_pos ); 289bad += (int )equiv_bad ; 290 291// 4d. YARN vs a float64 transcription of ggml's rope_yarn (factor 4, the default correction knobs). 292// The ramp helper is shared with the builder (the rope_neox_pair convention: one definition, not two 293// transcriptions of it); the interpolation mix and the mscale formula are written here from the ggml 294// source lines, which is the spec being tested. 295 strata::kernels::RopeScaling yarn ; 296yarn .type = strata::kernels::RopeScalingType ::YaRN ; 297yarn .freq_base = theta ; 298yarn .factor = 4.0 ; 299yarn .ext_factor = 1.0 ; 300 std::vector < float > yc ((size_t )max_pos * half ),ys ((size_t )max_pos * half ); 301 strata::kernels::build_rope_table (n_rot ,yarn ,max_pos ,yc .data (),ys .data ()); 302const double fs = yarn .freq_scale ();// 0.25 303const double ms = yarn .mscale ();// attn_factor * (1 + 0.1*ln(4)) 304double cd [2 ]; 305yarn .corr_dims (n_rot ,cd ); 306long long yarn_bad = 0 ; 307for (int p = 0 ;p < max_pos ;++ p ) { 308for (int i = 0 ;i < half ;++ i ) { 309const double inv = std::pow (theta ,-2.0 * (double )i / (double )n_rot ); 310const double extrap = (double )p * inv ; 311const double interp = fs * extrap ; 312const double ramp = (double ) strata::kernels::rope_yarn_ramp ((float )cd [0 ], (float )cd [1 ],i )* 313yarn .ext_factor ; 314const double ang = interp * (1.0 - ramp )+ extrap * ramp ; 315const float rc = (float ) (std::cos (ang )* ms ),rs = (float ) (std::sin (ang )* ms ); 316if (std::memcmp (& rc ,& yc [(size_t )p * half + i ],4 )!= 0 )++ yarn_bad ; 317if (std::memcmp (& rs ,& ys [(size_t )p * half + i ],4 )!= 0 )++ yarn_bad ; 318 } 319 } 320 std::printf (" scaled table, yarn factor 4 %s (%lld of %d entries differ)\n" , 321yarn_bad ?"*** WRONG ***" :"bit-exact" ,yarn_bad ,max_pos * half * 2 ); 322bad += (int )yarn_bad ; 323 324// 4e. THE STRUCTURE a tolerance cannot fake. At position 0 every pair's angle is 0, so YaRN's whole 325// magnitude correction stands naked: cos_tab[0] == mscale. At the far end of the table the first 326// pair (the highest trained frequency) must match EXTRAPOLATION and the last INTERPOLATION. The two 327// halves need different observables: at the first pair cos separates the hypotheses outright, but at 328// the last they differ by ~4 microradians here, invisible to cos near 1 - sin sees it, because near 329// zero sin IS the angle. That asymmetry is the YaRN design: interpolation happens where angles are 330// small. Both hypotheses go through the same mix formula the builder uses, so the bit comparison is 331// spec against spec, not shortcut against implementation. 332 { 333const float msv = (float )ms ; 334const bool zero_ok = std::memcmp (& msv ,& yc [0 ],4 )== 0 && ys [0 ]== 0.0f ; 335const int far = max_pos - 1 ; 336const double inv_f = 1.0 ;// pair 0: theta ** 0 337const double extrap_f = (double )far * inv_f ,interp_f = fs * extrap_f ; 338const double inv_l = std::pow (theta ,-2.0 * (double ) (half - 1 ) / (double )n_rot ); 339const double extrap_l = (double )far * inv_l ,interp_l = fs * extrap_l ; 340const float ef = (float ) (std::cos (interp_f * (1.0 - 1.0 )+ extrap_f * 1.0 )* ms ); 341const float itf = (float ) (std::cos (interp_f * (1.0 - 0.0 )+ extrap_f * 0.0 )* ms ); 342const float sl_e = (float ) (std::sin (interp_l * (1.0 - 1.0 )+ extrap_l * 1.0 )* ms ); 343const float sl_i = (float ) (std::sin (interp_l * (1.0 - 0.0 )+ extrap_l * 0.0 )* ms ); 344const float got_f = yc [(size_t )far * half ],got_l = ys [(size_t )far * half + (half - 1 )]; 345const bool first_extrapolates = std::memcmp (& got_f ,& ef ,4 )== 0 ; 346const bool last_interpolates = std::memcmp (& got_l ,& sl_i ,4 )== 0 ; 347const bool distinguishable = std::fabs ((double )ef - (double )itf )> 1e-3 && 348 std::fabs ((double )sl_e - (double )sl_i )> 1e-8 ; 349 std::printf (" yarn structure: cos_tab[0]==mscale %.4f, first pair extrapolates, last interpolates " 350"%s\n" , (double )msv , 351zero_ok && first_extrapolates && last_interpolates && distinguishable 352 ?"confirmed" 353 :"*** WRONG ***" ); 354if (!(zero_ok && first_extrapolates && last_interpolates && distinguishable ))++ bad ; 355 } 356 357// 4f. THE OBSERVABILITY assertion: the fixtures must SEE scaling. If the builder ignored its config, 358// linear(2) would equal `none` everywhere and 4b-4e would be green on a broken builder. 359 { 360 strata::kernels::RopeScaling lin2 ; 361lin2 .type = strata::kernels::RopeScalingType ::Linear ; 362lin2 .freq_base = theta ; 363lin2 .factor = 2.0 ; 364 std::vector < float > l2c ((size_t )101 * half ),l2s ((size_t )101 * half ); 365 strata::kernels::build_rope_table (n_rot ,lin2 ,101 ,l2c .data (),l2s .data ()); 366const float c_none = (float ) std::cos (100.0 );// pair 0, position 100, unscaled: ang = 100 367const float c_lin = l2c [(size_t )100 * half ];// pair 0, position 100, linear(2): ang = 50 368const bool sees = std::fabs ((double )c_none - (double )c_lin )> 1e-3 ; 369 std::printf (" observability: none vs linear(2) at position 100 %s (|%.4f - %.4f|)\n" , 370sees ?"visible" :"*** VACUUM ***" , (double )c_none , (double )c_lin ); 371if (!sees )++ bad ; 372 } 373 374// 4g. THE ROTATION under a scaled table. The kernel is table-agnostic and must not know or care: 375// the host reference is the same rope_neox_pair walk as check 2, over the YaRN table. 376 std::vector < float > ref2 (x .size ()); 377for (int r = 0 ;r < rows ;++ r ) { 378const float * xr = & x [(size_t )r * head_dim ]; 379float * orow = & ref2 [(size_t )r * head_dim ]; 380for (int d = 0 ;d < head_dim ;++ d )orow [d ]= xr [d ]; 381for (int i = 0 ;i < half ;++ i ) { 382float c = yc [(size_t )pos [(size_t )r ]* half + i ],s = ys [(size_t )pos [(size_t )r ]* half + i ]; 383 strata::kernels::rope_neox_pair (xr [i ],xr [half + i ],c ,s ,orow [i ],orow [half + i ]); 384 } 385 } 386/* 387DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, 388assuming in the original code the source host memory is pageable memory. 389If the memory is not pageable, call wait() on event return by memcpy API 390to ensure synchronization behavior. 391*/ 392check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy ( 393d_x ,x .data (),x .size ()* sizeof (float )).wait ()), 394"copy x" ); 395/* 396DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, 397assuming in the original code the source host memory is pageable memory. 398If the memory is not pageable, call wait() on event return by memcpy API 399to ensure synchronization behavior. 400*/ 401check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy ( 402d_cos ,yc .data (),yc .size ()* sizeof (float )).wait ()), 403"copy ycos" ); 404/* 405DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, 406assuming in the original code the source host memory is pageable memory. 407If the memory is not pageable, call wait() on event return by memcpy API 408to ensure synchronization behavior. 409*/ 410check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy ( 411d_sin ,ys .data (),ys .size ()* sizeof (float )).wait ()), 412"copy ysin" ); 413/* 414DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, 415assuming in the original code the source host memory is pageable memory. 416If the memory is not pageable, call wait() on event return by memcpy API 417to ensure synchronization behavior. 418*/ 419check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy ( 420d_pos ,pos .data (),pos .size ()* sizeof (int )).wait ()), 421"copy pos" ); 422 strata::kernels::rope_neox_apply (d_x ,d_out ,rows ,head_dim ,n_rot ,d_cos ,d_sin ,d_pos ,nullptr ); 423 std::vector < float > got2 (ref2 .size ()); 424check (DPCT_CHECK_ERROR ( 425 (dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()) 426 .memcpy (got2 .data (),d_out ,got2 .size ()* sizeof (float )) 427 .wait ()), 428"back" ); 429long long rot2_bad = 0 ; 430double worst2 = 0.0 ; 431for (size_t i = 0 ;i < ref2 .size ();++ i ) { 432const double a = ref2 [i ],b = got2 [i ]; 433const double rel = std::fabs (a - b ) /row_scale [i / (size_t )head_dim ]; 434worst2 = std::max (worst2 ,rel ); 435if (!(rel <=1e-6 ))++ rot2_bad ; 436 } 437 std::printf (" rope rotation over the yarn table %s (%lld of %zu over 1e-6, worst rel %.3e)\n" , 438rot2_bad ?"*** WRONG ***" :"agrees" ,rot2_bad ,ref2 .size (),worst2 ); 439bad += (int )rot2_bad ; 440 } 441 442// ---- 5. THE TWO PATHS MUST AGREE. The table path (the default) computes cos/sin on the host in float64; 443// the native path (`--native-rope`) computes the same angles on device in float32 under `--use_fast_math`. 444// They answer to ONE config - `RopeScaling` - and a disagreement between them would put differently-rotated 445// K into the cache depending on which path ran. The tolerance is NOT the 1e-6 of checks 2/4g: the device 446// side takes fast-math trig at angles up to ~2048 rad, where the fp32 range reduction alone is worth ~1e-4, 447// so the bar is the row-magnitude-relative 3e-3 and the test keeps the positions where that holds. (The 448// engine's default is the table path precisely because float64 host trig has no such floor.) 449 { 450const int npos = 2048 ; 451 strata::kernels::RopeScaling yarn ; 452yarn .type = strata::kernels::RopeScalingType ::YaRN ; 453yarn .factor = 2.0 ; 454yarn .ext_factor = 1.0 ; 455 std::vector < float > sc ((size_t )npos * half ),ss ((size_t )npos * half ); 456 strata::kernels::build_rope_table (n_rot ,yarn ,npos ,sc .data (),ss .data ()); 457 std::mt19937 rng2 (23 ); 458 std::normal_distribution < float > gauss2 (0.0f ,1.0f ); 459const int nrows = 24 * 16 ;// 16 positions spread over the table's range 460 std::vector < float > x2 ((size_t )nrows * head_dim ); 461for (auto & v :x2 )v = gauss2 (rng2 ); 462 std::vector < int > pos2 ((size_t )nrows ); 463for (int r = 0 ;r < nrows ;++ r )pos2 [(size_t )r ]= (r * 127 ) %npos ; 464 465float * d_x2 = nullptr ,* d_t2 = nullptr ,* d_n2 = nullptr ,* d_c2 = nullptr ,* d_s2 = nullptr ; 466int * d_p2 = nullptr ; 467check (DPCT_CHECK_ERROR (d_x2 = sycl::malloc_device < float > ( 468x2 .size (), dpct::get_in_order_queue ())), 469"malloc x2" ); 470check (DPCT_CHECK_ERROR (d_t2 = sycl::malloc_device < float > ( 471x2 .size (), dpct::get_in_order_queue ())), 472"malloc t2" ); 473check (DPCT_CHECK_ERROR (d_n2 = sycl::malloc_device < float > ( 474x2 .size (), dpct::get_in_order_queue ())), 475"malloc n2" ); 476check (DPCT_CHECK_ERROR (d_c2 = sycl::malloc_device < float > ( 477sc .size (), dpct::get_in_order_queue ())), 478"malloc c2" ); 479check (DPCT_CHECK_ERROR (d_s2 = sycl::malloc_device < float > ( 480ss .size (), dpct::get_in_order_queue ())), 481"malloc s2" ); 482check (DPCT_CHECK_ERROR (d_p2 = sycl::malloc_device < int > ( 483pos2 .size (), dpct::get_in_order_queue ())), 484"malloc p2" ); 485/* 486DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, 487assuming in the original code the source host memory is pageable memory. 488If the memory is not pageable, call wait() on event return by memcpy API 489to ensure synchronization behavior. 490*/ 491check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy ( 492d_x2 ,x2 .data (),x2 .size ()* sizeof (float )).wait ()), 493"copy x2" ); 494/* 495DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, 496assuming in the original code the source host memory is pageable memory. 497If the memory is not pageable, call wait() on event return by memcpy API 498to ensure synchronization behavior. 499*/ 500check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy ( 501d_c2 ,sc .data (),sc .size ()* sizeof (float )).wait ()), 502"copy c2" ); 503/* 504DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, 505assuming in the original code the source host memory is pageable memory. 506If the memory is not pageable, call wait() on event return by memcpy API 507to ensure synchronization behavior. 508*/ 509check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy ( 510d_s2 ,ss .data (),ss .size ()* sizeof (float )).wait ()), 511"copy s2" ); 512/* 513DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, 514assuming in the original code the source host memory is pageable memory. 515If the memory is not pageable, call wait() on event return by memcpy API 516to ensure synchronization behavior. 517*/ 518check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy ( 519d_p2 ,pos2 .data (),pos2 .size ()* sizeof (int )).wait ()), 520"copy p2" ); 521// The native path demands an explicit stream - a null one is refused by validation, not defaulted. 522 dpct::queue_ptr cs5 = & dpct::get_in_order_queue (); 523check (DPCT_CHECK_ERROR ( 524cs5 = dpct::get_current_device ().create_queue (true)), 525"stream5" ); 526 strata::kernels::rope_neox_apply (d_x2 ,d_t2 ,nrows ,head_dim ,n_rot ,d_c2 ,d_s2 ,d_p2 ,nullptr ); 527 strata::kernels::native_rope_apply (d_x2 ,d_n2 ,nrows ,head_dim ,n_rot ,yarn ,d_p2 ,cs5 ); 528check (DPCT_CHECK_ERROR (cs5 -> wait ()),"sync5" ); 529 std::vector < float > got_t (x2 .size ()),got_n (x2 .size ()); 530check (DPCT_CHECK_ERROR ( 531 (dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()) 532 .memcpy (got_t .data (),d_t2 ,got_t .size ()* sizeof (float )) 533 .wait ()), 534"back t2" ); 535check (DPCT_CHECK_ERROR ( 536 (dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()) 537 .memcpy (got_n .data (),d_n2 ,got_n .size ()* sizeof (float )) 538 .wait ()), 539"back n2" ); 540long long agree_bad = 0 ; 541double worst = 0.0 ; 542for (int r = 0 ;r < nrows ;++ r ) { 543double m = 0 ; 544for (int d = 0 ;d < head_dim ;++ d )m = std::max (m , (double ) std::fabs (x2 [(size_t )r * head_dim + d ])); 545const double scale = m > 1e-30 ?m :1e-30 ; 546for (int d = 0 ;d < head_dim ;++ d ) { 547const double rel = std::fabs ((double )got_t [(size_t )r * head_dim + d ]- 548 (double )got_n [(size_t )r * head_dim + d ]) /scale ; 549worst = std::max (worst ,rel ); 550if (!(rel <=3e-3 ))++ agree_bad ; 551 } 552 } 553 std::printf (" native path vs table path, yarn factor 2 %s (%lld of %d over 3e-3, worst rel %.3e)\n" , 554agree_bad ?"*** WRONG ***" :"agrees" ,agree_bad ,nrows * head_dim ,worst ); 555bad += (int )agree_bad ; 556 557// and the None config: the native path against the UNSCALED table - the identity this feature must 558// not disturb. 559 strata::kernels::RopeScaling none5 ;// all defaults: type None, freq_scale 1, mscale 1 560 strata::kernels::native_rope_apply (d_x2 ,d_n2 ,nrows ,head_dim ,n_rot ,none5 ,d_p2 ,cs5 ); 561check (DPCT_CHECK_ERROR (cs5 -> wait ()),"sync5b" ); 562check (DPCT_CHECK_ERROR ( 563 (dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()) 564 .memcpy (got_n .data (),d_n2 ,got_n .size ()* sizeof (float )) 565 .wait ()), 566"back n2b" ); 567 std::vector < float > nc5 ((size_t )npos * half ),ns5 ((size_t )npos * half ); 568 strata::kernels::build_rope_table (n_rot ,none5 ,npos ,nc5 .data (),ns5 .data ()); 569/* 570DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, 571assuming in the original code the source host memory is pageable memory. 572If the memory is not pageable, call wait() on event return by memcpy API 573to ensure synchronization behavior. 574*/ 575check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy ( 576d_c2 ,nc5 .data (),nc5 .size ()* sizeof (float )).wait ()), 577"copy c2b" ); 578/* 579DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, 580assuming in the original code the source host memory is pageable memory. 581If the memory is not pageable, call wait() on event return by memcpy API 582to ensure synchronization behavior. 583*/ 584check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy ( 585d_s2 ,ns5 .data (),ns5 .size ()* sizeof (float )).wait ()), 586"copy s2b" ); 587 strata::kernels::rope_neox_apply (d_x2 ,d_t2 ,nrows ,head_dim ,n_rot ,d_c2 ,d_s2 ,d_p2 ,nullptr ); 588check (DPCT_CHECK_ERROR ( 589 (dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()) 590 .memcpy (got_t .data (),d_t2 ,got_t .size ()* sizeof (float )) 591 .wait ()), 592"back t2b" ); 593long long none_bad5 = 0 ; 594double worst5 = 0.0 ; 595for (int r = 0 ;r < nrows ;++ r ) { 596double m = 0 ; 597for (int d = 0 ;d < head_dim ;++ d )m = std::max (m , (double ) std::fabs (x2 [(size_t )r * head_dim + d ])); 598const double scale = m > 1e-30 ?m :1e-30 ; 599for (int d = 0 ;d < head_dim ;++ d ) { 600const double rel = std::fabs ((double )got_t [(size_t )r * head_dim + d ]- 601 (double )got_n [(size_t )r * head_dim + d ]) /scale ; 602worst5 = std::max (worst5 ,rel ); 603if (!(rel <=3e-3 ))++ none_bad5 ; 604 } 605 } 606 std::printf (" native path vs table path, none %s (%lld of %d over 3e-3, worst rel %.3e)\n" , 607none_bad5 ?"*** WRONG ***" :"agrees" ,none_bad5 ,nrows * head_dim ,worst5 ); 608bad += (int )none_bad5 ; 609 610// ---- 6. FUSED RMSNorm + RoPE (`native_qsa_rms_norm_rope`) MUST BE BIT-IDENTICAL to 611// `native_qsa_rms_norm_weighted` followed by `native_rope_apply` for both contiguous 612// (`in_stride == head_dim`) and strided Q/gate split (`in_stride == 2 * head_dim`) inputs, 613// across supported head_dims (128, 256) and both unscaled and YaRN scaling. 614// The kernel is off by default on the HIP build until this check passes there (native_norm_rope_usable): the 615// check then reports SKIPPED, and STRATA_NORM_ROPE=1 runs it (gfx1151, Aurora, 0.1.40: it does not pass). 616const bool run6 = strata::kernels::native_norm_rope_usable (256 ,64 ); 617if (!run6 ) 618 std::printf (" native_qsa_rms_norm_rope SKIPPED (the fused kernel is not enabled on this build)\n" ); 619for (int hd6 : {128 ,256 }) { 620if (!run6 )break ; 621const int nr6 = 64 ; 622const int rows6 = 96 ; 623 std::vector < float > x6_strided ((size_t )rows6 * 2 * hd6 ); 624 std::vector < float > gamma6 ((size_t )hd6 ); 625 std::vector < int > pos6 ((size_t )rows6 ); 626for (auto & v :x6_strided )v = gauss2 (rng2 ); 627for (auto & g :gamma6 )g = 0.5f + std::fabs (gauss2 (rng2 )); 628for (int r = 0 ;r < rows6 ;++ r )pos6 [(size_t )r ]= (r * 53 + 1 ) %npos ; 629 630float * d_xs6 = nullptr ,* d_g6 = nullptr ,* d_ref6 = nullptr ,* d_fus6 = nullptr ; 631int * d_pos6 = nullptr ; 632check (DPCT_CHECK_ERROR ( 633d_xs6 = sycl::malloc_device < float > ( 634x6_strided .size (), dpct::get_in_order_queue ())), 635"malloc xs6" ); 636check (DPCT_CHECK_ERROR ( 637d_g6 = sycl::malloc_device < float > ( 638gamma6 .size (), dpct::get_in_order_queue ())), 639"malloc g6" ); 640check (DPCT_CHECK_ERROR ( 641d_ref6 = sycl::malloc_device < float > ( 642 (size_t )rows6 * hd6 , dpct::get_in_order_queue ())), 643"malloc ref6" ); 644check (DPCT_CHECK_ERROR ( 645d_fus6 = sycl::malloc_device < float > ( 646 (size_t )rows6 * hd6 , dpct::get_in_order_queue ())), 647"malloc fus6" ); 648check ( 649DPCT_CHECK_ERROR (d_pos6 = sycl::malloc_device < int > ( 650pos6 .size (), dpct::get_in_order_queue ())), 651"malloc pos6" ); 652/* 653DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, 654assuming in the original code the source host memory is pageable 655memory. If the memory is not pageable, call wait() on event return 656by memcpy API to ensure synchronization behavior. 657*/ 658check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy ( 659d_xs6 ,x6_strided .data (), 660x6_strided .size ()* sizeof (float )).wait ()), 661"copy xs6" ); 662/* 663DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, 664assuming in the original code the source host memory is pageable 665memory. If the memory is not pageable, call wait() on event return 666by memcpy API to ensure synchronization behavior. 667*/ 668check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy ( 669d_g6 ,gamma6 .data (),gamma6 .size ()* sizeof (float )).wait ()), 670"copy g6" ); 671/* 672DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, 673assuming in the original code the source host memory is pageable 674memory. If the memory is not pageable, call wait() on event return 675by memcpy API to ensure synchronization behavior. 676*/ 677check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy ( 678d_pos6 ,pos6 .data (),pos6 .size ()* sizeof (int )).wait ()), 679"copy pos6" ); 680 681long long fbad = 0 ; 682for (const auto & sc6 : {none5 ,yarn }) { 683// (a) strided Q/gate split (in_stride = 2 * hd6) vs cudaMemcpy2DAsync + norm + rope 684/* 685DPCT1124: cudaMemcpy2DAsync is migrated to asynchronous 686memcpy API. While the origin API might be synchronous, it 687depends on the type of operand memory, so you may need to call 688wait() on event return by memcpy API to ensure synchronization 689behavior. 690*/ 691check (DPCT_CHECK_ERROR (dpct::async_dpct_memcpy ( 692d_ref6 , (size_t )hd6 * sizeof (float ),d_xs6 , 693 (size_t )2 * hd6 * sizeof (float ), 694 (size_t )hd6 * sizeof (float ), (size_t )rows6 , 695 dpct::device_to_device ,* cs5 )), 696"split6" ); 697 strata::kernels::native_qsa_rms_norm_weighted (d_ref6 ,d_g6 ,d_ref6 ,hd6 ,rows6 ,1e-6f ,cs5 ); 698 strata::kernels::native_rope_apply (d_ref6 ,d_ref6 ,rows6 ,hd6 ,nr6 ,sc6 ,d_pos6 ,cs5 ); 699 700 strata::kernels::native_qsa_rms_norm_rope (d_xs6 ,2 * hd6 ,d_g6 ,d_fus6 ,rows6 ,hd6 ,nr6 ,1e-6f ,sc6 , 701d_pos6 ,cs5 ); 702check (DPCT_CHECK_ERROR (cs5 -> wait ()),"sync6a" ); 703 std::vector < float > href ((size_t )rows6 * hd6 ),hfus ((size_t )rows6 * hd6 ); 704check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()) 705 .memcpy (href .data (),d_ref6 , 706href .size ()* sizeof (float )) 707 .wait ()), 708"back ref6a" ); 709check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()) 710 .memcpy (hfus .data (),d_fus6 , 711hfus .size ()* sizeof (float )) 712 .wait ()), 713"back fus6a" ); 714for (size_t i = 0 ;i < href .size ();++ i ) { 715if (std::memcmp (& href [i ],& hfus [i ],4 )!= 0 )++ fbad ; 716 } 717 718// (b) contiguous in-place (in_stride = hd6, output == input) 719/* 720DPCT1124: cudaMemcpy2DAsync is migrated to asynchronous 721memcpy API. While the origin API might be synchronous, it 722depends on the type of operand memory, so you may need to call 723wait() on event return by memcpy API to ensure synchronization 724behavior. 725*/ 726check (DPCT_CHECK_ERROR (dpct::async_dpct_memcpy ( 727d_ref6 , (size_t )hd6 * sizeof (float ),d_xs6 , 728 (size_t )2 * hd6 * sizeof (float ), 729 (size_t )hd6 * sizeof (float ), (size_t )rows6 , 730 dpct::device_to_device ,* cs5 )), 731"contig6_ref" ); 732check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy ( 733d_fus6 ,d_ref6 , (size_t )rows6 * hd6 * sizeof (float )).wait ()), 734"contig6_fus" ); 735 strata::kernels::native_qsa_rms_norm_weighted (d_ref6 ,d_g6 ,d_ref6 ,hd6 ,rows6 ,1e-6f ,cs5 ); 736 strata::kernels::native_rope_apply (d_ref6 ,d_ref6 ,rows6 ,hd6 ,nr6 ,sc6 ,d_pos6 ,cs5 ); 737 strata::kernels::native_qsa_rms_norm_rope (d_fus6 ,hd6 ,d_g6 ,d_fus6 ,rows6 ,hd6 ,nr6 ,1e-6f ,sc6 , 738d_pos6 ,cs5 ); 739check (DPCT_CHECK_ERROR (cs5 -> wait ()),"sync6b" ); 740check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()) 741 .memcpy (href .data (),d_ref6 , 742href .size ()* sizeof (float )) 743 .wait ()), 744"back ref6b" ); 745check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()) 746 .memcpy (hfus .data (),d_fus6 , 747hfus .size ()* sizeof (float )) 748 .wait ()), 749"back fus6b" ); 750for (size_t i = 0 ;i < href .size ();++ i ) { 751if (std::memcmp (& href [i ],& hfus [i ],4 )!= 0 )++ fbad ; 752 } 753 } 754 std::printf (" native_qsa_rms_norm_rope hd=%3d nr=%2d %s (%lld of %d elements differ)\n" , 755hd6 ,nr6 ,fbad ?"*** WRONG ***" :"bit-identical" ,fbad ,rows6 * hd6 * 4 ); 756bad += (int )fbad ; 757 sycl::free (d_xs6 , dpct::get_in_order_queue ()); 758 sycl::free (d_g6 , dpct::get_in_order_queue ()); 759 sycl::free (d_ref6 , dpct::get_in_order_queue ()); 760 sycl::free (d_fus6 , dpct::get_in_order_queue ()); 761 sycl::free (d_pos6 , dpct::get_in_order_queue ()); 762 } 763 } 764 765 std::printf ("\nrope: %d failures\n" ,bad ); 766if (bad )return 1 ; 767if (selftest ) std::printf ("rope_parity OK\n" ); 768return 0 ; 769}