okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
ad33b8074
main
1// src/kernels/elementwise_parity.cpp - P2.S5's test for the layer glue. 2// 3// The ops are small; the CONVENTIONS in them are not, and each one is a place where a plausible reading 4// gives a plausible number: 5// 6// 1. `softplus` HAS A LARGE-x BRANCH. `log1p(exp(x))` overflows f32 at x > 88 and loses relative precision 7// well before that; `ggml_compute_softplus_f32` returns `x` above 20. A rival without the branch is 8// asserted observable, because a gate that saturates to +inf makes `exp(gate)` inf and the whole 9// recurrence NaN - which reads as a state bug and not as a missing branch. 10// 2. `ssm_a` IS NEGATIVE. `gate = softplus(...) * ssm_a`, so `exp(gate) < 1` and the state DECAYS. A 11// fixture with a positive `ssm_a` would still produce finite output and the recurrence would blow up 12// instead of decaying, so the sign is checked as a property and not assumed. 13// 3. `silu` IS COMPUTED IN DOUBLE then cast, because `ref/gdn.py`'s numpy does. f32 `expf` differs in the 14// last bits, and the test measures that rather than asserting it away. 15#define DPCT_PROFILING_ENABLED 16#include <sycl/sycl.hpp> 17#include <dpct/dpct.hpp> 18#include "strata/kernels/dequant_bf16.hpp" 19#include "strata/kernels/elementwise.hpp" 20#include "strata/kernels/f16_bits.hpp" 21 22#include <cmath> 23#include <cstdio> 24#include <cstdlib> 25#include <cstring> 26#include <random> 27#include <string> 28#include <vector> 29 30namespace { 31 32void check (dpct::err0 e ,const char * what ) { 33} 34 35double rel_l1 (const std::vector < float >& a ,const std::vector < float >& b ) { 36double d = 0 ,m = 0 ; 37for (size_t i = 0 ;i < a .size ();++ i ) { 38d += std::fabs ((double )a [i ]- (double )b [i ]); 39m += std::fabs ((double )a [i ]); 40 } 41return d / (m > 1e-30 ?m :1e-30 ); 42} 43 44}// namespace 45 46int main (int argc ,char ** argv ) { 47bool selftest = false; 48for (int i = 1 ;i < argc ;++ i ) { 49if (std::string (argv [i ])== "--selftest" )selftest = true; 50else { std::fprintf (stderr ,"usage: elementwise_parity [--selftest]\n" );return 2 ; } 51 } 52int bad = 0 ; 53const int64_t H_V = 48 ; 54 55// ---- 1. gdn_gate, with the reference's own softplus 56 { 57const int n = (int )H_V ; 58 std::mt19937 rng (11 ); 59 std::normal_distribution < float > g (0.0f ,1.0f ); 60 std::vector < float > alpha (n ),dt (n ),a (n ),want (n ); 61for (int i = 0 ;i < n ;++ i ) { 62// A MIXTURE THAT ACTUALLY CROSSES THE BRANCH. The first version drew alpha from a normal with 63// sigma 3, so the largest value was about 9 and `softplus` never took its `x > 20` path - the 64// "branch is observable" check then reported **0.00% apart, 0 non-finite**, which is the fixture 65// saying it cannot see the thing it was written to see. Every third head is now large. 66const bool large = (i %3 )== 0 ; 67// Up to ~120, so the fixture spans WELL PAST f32's `exp` overflow at 88. A fixture that stopped 68// at 88 would show the branch as unobservable and would be right: `log1pf(expf(x))` equals `x` to 69// f32 precision for the whole range 20..88, so ggml's threshold of 20 is CONSERVATIVE and the 70// behaviour only actually changes where `expf` overflows. 71alpha [i ]= large ? (22.0f + 6.0f * (float ) (i %17 )) :g (rng )* 3.0f ; 72dt [i ]= g (rng )* 0.5f ; 73// NEGATIVE, as the artifact's `ssm_a = -exp(A_log)` is. Checked below as a property. 74a [i ]= - (std::fabs (g (rng ))+ 0.1f ); 75const double x = (double )alpha [i ]+ (double )dt [i ]; 76const double sp = x > 20.0 ?x : std::log1p (std::exp (x )); 77want [(size_t )i ]= (float ) (sp * (double )a [i ]); 78 } 79// the fixture must EXERCISE the branch, or check 1 below measures nothing 80 { 81int over = 0 ,past_overflow = 0 ; 82for (int i = 0 ;i < n ;++ i ) { 83const float x = alpha [(size_t )i ]+ dt [(size_t )i ]; 84if (x > 20.0f )++ over ; 85if (x > 88.0f )++ past_overflow ; 86 } 87 std::printf (" %-44s %s (%d above 20, %d above 88)\n" ,"the fixture crosses the branch" , 88over ?"yes" :"*** NO ***" ,over ,past_overflow ); 89if (!over )++ bad ; 90 } 91// the sign property, asserted rather than assumed 92int positive = 0 ; 93for (int i = 0 ;i < n ;++ i )if (a [(size_t )i ] >=0.0f )++ positive ; 94 std::printf (" %-44s %s (%d of %d non-negative)\n" ,"the fixture's ssm_a is negative" , 95positive ?"*** NO ***" :"yes" ,positive ,n ); 96if (positive )++ bad ; 97 98float * d_a = nullptr ,* d_dt = nullptr ,* d_sa = nullptr ,* d_g = nullptr ; 99check (DPCT_CHECK_ERROR (d_a = (float * )sycl::malloc_device ( 100n * 4 , dpct::get_in_order_queue ())), 101"a" ); 102check (DPCT_CHECK_ERROR (d_dt = (float * )sycl::malloc_device ( 103n * 4 , dpct::get_in_order_queue ())), 104"dt" ); 105check (DPCT_CHECK_ERROR (d_sa = (float * )sycl::malloc_device ( 106n * 4 , dpct::get_in_order_queue ())), 107"sa" ); 108check (DPCT_CHECK_ERROR (d_g = (float * )sycl::malloc_device ( 109n * 4 , dpct::get_in_order_queue ())), 110"g" ); 111/* 112DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, 113assuming in the original code the source host memory is pageable memory. 114If the memory is not pageable, call wait() on event return by memcpy API 115to ensure synchronization behavior. 116*/ 117check (DPCT_CHECK_ERROR ( 118 (dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy (d_a ,alpha .data (),n * 4 ).wait ()), 119"ca" ); 120/* 121DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, 122assuming in the original code the source host memory is pageable memory. 123If the memory is not pageable, call wait() on event return by memcpy API 124to ensure synchronization behavior. 125*/ 126check (DPCT_CHECK_ERROR ( 127 (dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy (d_dt ,dt .data (),n * 4 ).wait ()), 128"cd" ); 129/* 130DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, 131assuming in the original code the source host memory is pageable memory. 132If the memory is not pageable, call wait() on event return by memcpy API 133to ensure synchronization behavior. 134*/ 135check (DPCT_CHECK_ERROR ( 136 (dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy (d_sa ,a .data (),n * 4 ).wait ()), 137"cs" ); 138 strata::kernels::gdn_gate (d_a ,d_dt ,d_sa ,d_g ,1 ,H_V ,nullptr ); 139 std::vector < float > got ((size_t )n ); 140check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()) 141 .memcpy (got .data (),d_g ,n * 4 ) 142 .wait ()), 143"cg" ); 144 145const double rel = rel_l1 (want ,got ); 146 std::printf (" %-44s rel %.3e\n" ,"gdn_gate vs the reference" ,rel ); 147// double softplus and double multiply on both sides, then one cast 148if (!(rel <=1e-6 )) { std::printf (" *** over 1e-6 ***\n" );++ bad ; } 149 150// TRAP: no large-x branch. `log1p(exp(x))` in f32, with no `x > 20` path. 151// 152// AND THE MEASUREMENT SAYS WHERE THE BRANCH ACTUALLY MATTERS. The first version of this fixture 153// spanned 20..88 and reported **0 heads differ**: `log1pf(expf(x))` agrees with `x` to f32 precision 154// over that whole range, so ggml's threshold of 20 is CONSERVATIVE - the branch changes the answer only 155// where `expf` OVERFLOWS, at about 88. The check reports the smallest x at which the two readings 156// part company, so the number is in the output rather than in this comment. 157 { 158int wrong = 0 ,differing = 0 ; 159float first_differ = -1.0f ; 160 std::vector < float > rival ((size_t )n ); 161for (int i = 0 ;i < n ;++ i ) { 162const float x = alpha [(size_t )i ]+ dt [(size_t )i ]; 163const float sp = std::log1p (std::exp (x ));// no branch, f32 164rival [(size_t )i ]= sp * a [(size_t )i ]; 165if (!std::isfinite (sp ))++ wrong ; 166const float branched = x > 20.0f ?x : std::log1pf (std::exp (x )); 167if (sp != branched ) { 168++ differing ; 169if (first_differ < 0.0f || x < first_differ )first_differ = x ; 170 } 171 } 172const double r = rel_l1 (want ,rival ); 173const bool visible = r > 0.05 || wrong > 0 ; 174 std::printf (" %-44s %s (%.2f%% apart, %d non-finite, %d heads differ, first at x = %.1f)\n" , 175"the softplus large-x branch is observable" ,visible ?"yes" :"*** NO ***" , 176r * 100 ,wrong ,differing , (double )first_differ ); 177if (!visible )++ bad ; 178 } 179// PROPERTY: exp(gate) < 1 for every element, which is what makes the state decay 180 { 181int over = 0 ; 182for (float v :got )if (!(std::exp (v )< 1.0f ))++ over ; 183 std::printf (" %-44s %s (%d of %d not < 1)\n" ,"exp(gate) < 1 for every head" , 184over ?"*** NO ***" :"yes" ,over ,n ); 185if (over )++ bad ; 186 } 187 sycl::free (d_a , dpct::get_in_order_queue ()); 188 sycl::free (d_dt , dpct::get_in_order_queue ()); 189 sycl::free (d_sa , dpct::get_in_order_queue ()); 190 sycl::free (d_g , dpct::get_in_order_queue ()); 191 } 192 193// ---- 2. silu, in double then cast 194 { 195const int n = 4096 ; 196 std::mt19937 rng (22 ); 197 std::normal_distribution < float > g (0.0f ,3.0f ); 198 std::vector < float > x ((size_t )n ),want ((size_t )n ); 199for (int i = 0 ;i < n ;++ i ) { 200x [(size_t )i ]= g (rng ); 201const double v = (double )x [(size_t )i ]; 202want [(size_t )i ]= (float ) (v / (1.0 + std::exp (- v ))); 203 } 204float * d_x = nullptr ; 205check (DPCT_CHECK_ERROR (d_x = (float * )sycl::malloc_device ( 206n * 4 , dpct::get_in_order_queue ())), 207"sx" ); 208/* 209DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, 210assuming in the original code the source host memory is pageable memory. 211If the memory is not pageable, call wait() on event return by memcpy API 212to ensure synchronization behavior. 213*/ 214check (DPCT_CHECK_ERROR ( 215 (dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy (d_x ,x .data (),n * 4 ).wait ()), 216"csx" ); 217 strata::kernels::silu_inplace (d_x ,n ,nullptr ); 218 std::vector < float > got ((size_t )n ); 219check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()) 220 .memcpy (got .data (),d_x ,n * 4 ) 221 .wait ()), 222"csg" ); 223const double rel = rel_l1 (want ,got ); 224 std::printf ("\n %-44s rel %.3e\n" ,"silu (double) vs the reference" ,rel ); 225if (!(rel <=1e-7 )) { std::printf (" *** over 1e-7 ***\n" );++ bad ; } 226 sycl::free (d_x , dpct::get_in_order_queue ()); 227 } 228 229// ---- 3. scale and the f32->f16 bridge 230 { 231const int n = 1024 ; 232 std::vector < float > x ((size_t )n ),want ((size_t )n ); 233for (int i = 0 ;i < n ;++ i )x [(size_t )i ]= (float ) (i - n /2 )* 0.013f ; 234const float s = 1.0f / std::sqrt (128.0f ); 235for (int i = 0 ;i < n ;++ i )want [(size_t )i ]= x [(size_t )i ]* s ; 236 237float * d_x = nullptr ; 238uint16_t * d_h = nullptr ; 239check (DPCT_CHECK_ERROR (d_x = (float * )sycl::malloc_device ( 240n * 4 , dpct::get_in_order_queue ())), 241"ex" ); 242check (DPCT_CHECK_ERROR (d_h = (uint16_t * )sycl::malloc_device ( 243n * 2 , dpct::get_in_order_queue ())), 244"eh" ); 245/* 246DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, 247assuming in the original code the source host memory is pageable memory. 248If the memory is not pageable, call wait() on event return by memcpy API 249to ensure synchronization behavior. 250*/ 251check (DPCT_CHECK_ERROR ( 252 (dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy (d_x ,x .data (),n * 4 ).wait ()), 253"cex" ); 254 strata::kernels::scale_inplace (d_x ,n ,s ,nullptr ); 255 std::vector < float > got ((size_t )n ); 256check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()) 257 .memcpy (got .data (),d_x ,n * 4 ) 258 .wait ()), 259"ceg" ); 260int diff = 0 ; 261for (int i = 0 ;i < n ;++ i )if (got [(size_t )i ]!= want [(size_t )i ])++ diff ; 262 std::printf (" %-44s %d of %d differ\n" ,"scale_inplace is exact" ,diff ,n ); 263if (diff )++ bad ; 264 265 strata::kernels::f32_to_f16_bulk (d_x ,d_h ,n ,nullptr ); 266 std::vector < uint16_t > h ((size_t )n ); 267check ( 268DPCT_CHECK_ERROR ( 269 (dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy (h .data (),d_h ,n * 2 ).wait ()), 270"ceh" ); 271int hbad = 0 ; 272for (int i = 0 ;i < n ;++ i ) 273if (h [(size_t )i ]!= strata::kernels::f16_from_f32 (got [(size_t )i ]))++ hbad ; 274 std::printf (" %-44s %d of %d differ\n" ,"f32_to_f16_bulk uses the shared conversion" ,hbad ,n ); 275if (hbad )++ bad ; 276 sycl::free (d_x , dpct::get_in_order_queue ()); 277 sycl::free (d_h , dpct::get_in_order_queue ()); 278 } 279 280// ---- 4. rms_norm_weighted, and the TWO RIVAL READINGS it exists to be told apart from. 281// 282// This kernel's whole reason for being a separate entry point from `gdn_l2_norm` is that the two differ by 283// one `/ cols`, and that a swap produces a well-scaled, plausible tensor. So the test computes BOTH wrong 284// readings and requires each to differ from the right one by more than the tolerance before it judges the 285// kernel - the same discipline the shared-expert test uses for silu-on-gate. 286 { 287const int64_t rows = 24 ,cols = 256 ;// the real `attn_q`-norm shape 288const float eps = 1e-6f ; 289 std::vector < float > x ((size_t ) (rows * cols )); 290for (size_t i = 0 ;i < x .size ();++ i )x [i ]= (float ) std::sin ((double )i * 0.017 )* 1.7f + 0.4f ; 291 std::vector < float > w ((size_t )cols ); 292for (int64_t c = 0 ;c < cols ;++ c )w [(size_t )c ]= 0.5f + 0.002f * (float ) (c %97 ); 293 294// the oracle: f64, mean, times w 295auto ref = [& ](bool use_sum ,bool use_w ) { 296 std::vector < double > y ((size_t ) (rows * cols )); 297for (int64_t r = 0 ;r < rows ;++ r ) { 298double ss = 0 ; 299for (int64_t c = 0 ;c < cols ;++ c ) { 300const double v = x [(size_t ) (r * cols + c )]; 301ss += v * v ; 302 } 303const double den = std::sqrt ((use_sum ?ss :ss / (double )cols )+ (double )eps ); 304for (int64_t c = 0 ;c < cols ;++ c ) { 305const double v = x [(size_t ) (r * cols + c )]; 306y [(size_t ) (r * cols + c )]= (v /den )* (use_w ? (double )w [(size_t )c ] :1.0 ); 307 } 308 } 309 std::vector < float > out ((size_t ) (rows * cols )); 310for (size_t i = 0 ;i < out .size ();++ i )out [i ]= (float )y [i ]; 311return out ; 312 }; 313const std::vector < float > want = ref (false, true); 314const std::vector < float > rival_sum = ref (true, false);// what gdn_l2_norm computes 315const std::vector < float > rival_now = ref (false, false);// the (1+w)-vs-w / no-weight confusion 316 317auto rel = [& ](const std::vector < float >& a ,const std::vector < float >& b ) { 318double d = 0 ,m = 0 ; 319for (size_t i = 0 ;i < a .size ();++ i ) { 320d += std::fabs ((double )a [i ]- (double )b [i ]); 321m += std::fabs ((double )a [i ]); 322 } 323return d / (m > 1e-30 ?m :1e-30 ); 324 }; 325const double r_sum = rel (want ,rival_sum ),r_now = rel (want ,rival_now ); 326 std::printf (" %-44s %.2f%% apart\n" ,"sum-vs-mean is observable" ,r_sum * 100 ); 327 std::printf (" %-44s %.2f%% apart\n" ,"with-w-vs-without-w is observable" ,r_now * 100 ); 328// `sqrt(cols)` = 16 for the first and the weight's own spread for the second; a fixture that cannot 329// separate them is not testing the kernel that was written. 330if (!(r_sum > 0.5 )) { std::printf (" *** the sum reading is NOT observable ***\n" );++ bad ; } 331if (!(r_now > 0.5 )) { std::printf (" *** the no-weight reading is NOT observable ***\n" );++ bad ; } 332 333float * d_x = nullptr ; 334float * d_w = nullptr ; 335check (DPCT_CHECK_ERROR (d_x = (float * )sycl::malloc_device ( 336x .size ()* 4 , dpct::get_in_order_queue ())), 337"m rmsx" ); 338check (DPCT_CHECK_ERROR (d_w = (float * )sycl::malloc_device ( 339w .size ()* 4 , dpct::get_in_order_queue ())), 340"m rmsw" ); 341/* 342DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, 343assuming in the original code the source host memory is pageable memory. 344If the memory is not pageable, call wait() on event return by memcpy API 345to ensure synchronization behavior. 346*/ 347check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy (d_x ,x .data (), 348x .size ()* 4 ).wait ()), 349"c rmsx" ); 350/* 351DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, 352assuming in the original code the source host memory is pageable memory. 353If the memory is not pageable, call wait() on event return by memcpy API 354to ensure synchronization behavior. 355*/ 356check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy (d_w ,w .data (), 357w .size ()* 4 ).wait ()), 358"c rmsw" ); 359 strata::kernels::rms_norm_weighted (d_x ,d_w ,rows ,cols ,eps ,nullptr ); 360 std::vector < float > got ((size_t ) (rows * cols )); 361check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()) 362 .memcpy (got .data (),d_x ,got .size ()* 4 ) 363 .wait ()), 364"c rmsg" ); 365 366const double r_got = rel (want ,got ); 367double worst = 0 ; 368for (size_t i = 0 ;i < got .size ();++ i ) { 369const double m = std::fabs ((double )want [i ]); 370const double e = std::fabs ((double )got [i ]- (double )want [i ]) / (m > 1e-30 ?m :1e-30 ); 371if (e > worst )worst = e ; 372 } 373int nonfinite = 0 ; 374for (float v :got )if (!std::isfinite (v ))++ nonfinite ; 375 std::printf (" %-44s rel %.3e worst %.3e nonfinite %d\n" ,"rms_norm_weighted vs f64 oracle" ,r_got , 376worst ,nonfinite ); 377if (nonfinite )++ bad ; 378// The kernel accumulates in f32 over 256 terms; 1e-6 is loose enough for that and far tighter than the 379// 16x the rival readings are off by. 380if (!(r_got < 1e-6 )) { std::printf (" *** rms_norm_weighted is WRONG ***\n" );++ bad ; } 381// and a null `w` must be legal, because `ref/qsa.py` allows it. 382// 383// THE INPUT HAS TO BE RE-UPLOADED FIRST. The kernel is IN PLACE, so `d_x` currently holds the 384// NORMALISED tensor from the call above; running it again normalises a second time and every element 385// differs. That is exactly what the first version of this check reported - "6144 of 6144 differ" - 386// and it is a fixture bug rather than a kernel bug: the oracle reads the ORIGINAL `x`, so the two 387// sides were never looking at the same input. 388const std::vector < float > want_null = ref (false, false); 389/* 390DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, 391assuming in the original code the source host memory is pageable memory. 392If the memory is not pageable, call wait() on event return by memcpy API 393to ensure synchronization behavior. 394*/ 395check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy (d_x ,x .data (), 396x .size ()* 4 ).wait ()), 397"c rmsx2" ); 398 strata::kernels::rms_norm_weighted (d_x ,nullptr ,rows ,cols ,eps ,nullptr ); 399check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()) 400 .memcpy (got .data (),d_x ,got .size ()* 4 ) 401 .wait ()), 402"c rmsn" ); 403int null_bad = 0 ; 404for (size_t i = 0 ;i < got .size ();++ i ) 405if (std::fabs ((double )got [i ]- (double )want_null [i ])> 1e-6 )++ null_bad ; 406 std::printf (" %-44s %d of %zu differ\n" ,"a null weight is legal" ,null_bad ,got .size ()); 407if (null_bad )++ bad ; 408 sycl::free (d_x , dpct::get_in_order_queue ()); 409 sycl::free (d_w , dpct::get_in_order_queue ()); 410 } 411 412// Packed embedding rows: every code width, scale-group size, optional offset, 413// row boundary and partial CUDA block. Compare bits with a scalar CPU decoder. 414// Volatile materializes the multiply so this oracle cannot silently use FMA. 415 { 416 dpct::queue_ptr stream ; 417/* 418DPCT1025: The SYCL queue is created ignoring the flag and priority 419options. 420*/ 421check (DPCT_CHECK_ERROR ( 422stream = dpct::get_current_device ().create_queue (true)), 423"embedding stream" ); 424 std::mt19937 rng (77 ); 425 std::uniform_real_distribution < float > values (-2.0f ,2.0f ); 426int mismatches = 0 ,guards = 0 ,fma_diff = 0 ,cases = 0 ; 427for (const int bits : {2 ,4 ,8 }) { 428const int bias = bits == 2 ?-1 :bits == 4 ?-7 :-16 ; 429const int per_byte = 8 /bits ; 430const unsigned mask = (1u <<bits )- 1u ; 431for (const int group : {16 ,32 ,64 }) { 432for (const int n : {320 ,2560 }) { 433const int row_bytes = n /per_byte ,row_groups = n /group ; 434 std::vector < uint8_t > codes ((size_t )3 * row_bytes ,0 ); 435 std::vector < float > scales ((size_t )3 * row_groups ),offsets (scales .size ()); 436 std::vector < int > unpacked ((size_t )3 * n ); 437for (size_t i = 0 ;i < unpacked .size ();++ i ) { 438const unsigned code = (unsigned ) (i * 13 + i /n * 7 )& mask ; 439unpacked [i ]= (int )code ; 440codes [i /per_byte ] |= (uint8_t ) (code << ((i %per_byte )* bits )); 441 } 442for (size_t i = 0 ;i < scales .size ();++ i ) { 443scales [i ]= values (rng ); 444offsets [i ]= values (rng ); 445 } 446scales [0 ]= -0.0f ; 447offsets [0 ]= 0.0f ; 448uint8_t * dc = nullptr ; 449float * ds = nullptr ,* dof = nullptr ,* out = nullptr ; 450check (DPCT_CHECK_ERROR ( 451dc = (uint8_t * )sycl::malloc_device ( 452codes .size (), dpct::get_in_order_queue ())), 453"embedding codes" ); 454check (DPCT_CHECK_ERROR ( 455ds = sycl::malloc_device < float > ( 456scales .size (), dpct::get_in_order_queue ())), 457"embedding scales" ); 458check (DPCT_CHECK_ERROR ( 459dof = sycl::malloc_device < float > ( 460offsets .size (), dpct::get_in_order_queue ())), 461"embedding offsets" ); 462check (DPCT_CHECK_ERROR ( 463out = sycl::malloc_device < float > ( 464 ((size_t )n + 2 ), dpct::get_in_order_queue ())), 465"embedding output" ); 466/* 467DPCT1124: cudaMemcpyAsync is migrated to asynchronous 468memcpy API. While the origin API might be synchronous, it 469depends on the type of operand memory, so you may need to 470call wait() on event return by memcpy API to ensure 471synchronization behavior. 472*/ 473check (DPCT_CHECK_ERROR ( 474stream -> memcpy (dc ,codes .data (),codes .size ())), 475"embedding codes upload" ); 476/* 477DPCT1124: cudaMemcpyAsync is migrated to asynchronous 478memcpy API. While the origin API might be synchronous, it 479depends on the type of operand memory, so you may need to 480call wait() on event return by memcpy API to ensure 481synchronization behavior. 482*/ 483check ( 484DPCT_CHECK_ERROR (stream -> memcpy ( 485ds ,scales .data (),scales .size ()* sizeof (float ))), 486"embedding scales upload" ); 487/* 488DPCT1124: cudaMemcpyAsync is migrated to asynchronous 489memcpy API. While the origin API might be synchronous, it 490depends on the type of operand memory, so you may need to 491call wait() on event return by memcpy API to ensure 492synchronization behavior. 493*/ 494check (DPCT_CHECK_ERROR ( 495stream -> memcpy (dof ,offsets .data (), 496offsets .size ()* sizeof (float ))), 497"embedding offsets upload" ); 498check (DPCT_CHECK_ERROR (stream -> wait ()), 499"embedding upload sync" ); 500 501for (const bool with_offset : {false, true}) { 502for (int row = 0 ;row < 3 ;++ row ) { 503 std::vector < float > want ((size_t )n ),got ((size_t )n + 2 ,-12345.0f ); 504for (int i = 0 ;i < n ;++ i ) { 505const size_t gi = (size_t )row * row_groups + i /group ; 506const float code = (float ) (unpacked [(size_t )row * n + i ]+ bias ); 507volatile float product = code * scales [gi ]; 508const float offset = with_offset ?offsets [gi ] :0.0f ; 509want [(size_t )i ]= product + offset ; 510const float fused = std::fma (code ,scales [gi ],offset ); 511if (std::memcmp (& fused ,& want [(size_t )i ],sizeof (float ))!= 0 )++ fma_diff ; 512 } 513/* 514DPCT1124: cudaMemcpyAsync is migrated to 515asynchronous memcpy API. While the origin API might 516be synchronous, it depends on the type of operand 517memory, so you may need to call wait() on event 518return by memcpy API to ensure synchronization 519behavior. 520*/ 521check (DPCT_CHECK_ERROR (stream -> memcpy ( 522out ,got .data (), 523got .size ()* sizeof (float ))), 524"embedding output guards" ); 525 strata::kernels::embedding_gather (dc + (size_t )row * row_bytes , 526ds + (size_t )row * row_groups , 527with_offset ?dof + (size_t )row * row_groups :nullptr , 528n ,bits ,bias ,group ,out + 1 ,stream ); 529/* 530DPCT1124: cudaMemcpyAsync is migrated to 531asynchronous memcpy API. While the origin API might 532be synchronous, it depends on the type of operand 533memory, so you may need to call wait() on event 534return by memcpy API to ensure synchronization 535behavior. 536*/ 537check (DPCT_CHECK_ERROR (stream -> memcpy ( 538got .data (),out , 539got .size ()* sizeof (float ))), 540"embedding result" ); 541check (DPCT_CHECK_ERROR (stream -> wait ()), 542"embedding sync" ); 543for (int i = 0 ;i < n ;++ i ) { 544if (std::memcmp (& want [(size_t )i ],& got [(size_t )i + 1 ],sizeof (float ))!= 0 )++ mismatches ; 545 } 546if (got .front ()!= -12345.0f || got .back ()!= -12345.0f )++ guards ; 547++ cases ; 548 549// Capturing the gather proves that it has no hidden synchronization. 550// A following scale also checks that it uses the caller's stream. 551if (row == 1 ) { 552 dpct::experimental::command_graph_ptr graph ; 553 dpct::experimental::command_graph_exec_ptr exec ; 554check (DPCT_CHECK_ERROR ( 555 dpct::experimental::begin_recording ( 556stream )), 557"embedding capture" ); 558 strata::kernels::embedding_gather (dc + (size_t )row * row_bytes , 559ds + (size_t )row * row_groups , 560with_offset ?dof + (size_t )row * row_groups :nullptr , 561n ,bits ,bias ,group ,out + 1 ,stream ); 562 strata::kernels::scale_inplace (out + 1 ,n ,2.0f ,stream ); 563check (DPCT_CHECK_ERROR ( 564 dpct::experimental::end_recording ( 565stream ,& graph )), 566"embedding capture end" ); 567check ( 568DPCT_CHECK_ERROR ( 569exec = new sycl::ext::oneapi:: 570 experimental::command_graph < 571 sycl::ext::oneapi:: 572 experimental::graph_state:: 573executable > ( 574graph -> finalize ())), 575"embedding instantiate" ); 576check (DPCT_CHECK_ERROR ( 577stream -> ext_oneapi_graph (* exec )), 578"embedding replay" ); 579/* 580DPCT1124: cudaMemcpyAsync is migrated to 581asynchronous memcpy API. While the origin API 582might be synchronous, it depends on the type of 583operand memory, so you may need to call wait() 584on event return by memcpy API to ensure 585synchronization behavior. 586*/ 587check (DPCT_CHECK_ERROR (stream -> memcpy ( 588got .data (),out , 589got .size ()* sizeof (float ))), 590"embedding graph result" ); 591check (DPCT_CHECK_ERROR (stream -> wait ()), 592"embedding graph sync" ); 593for (int i = 0 ;i < n ;++ i ) { 594const float expected = want [(size_t )i ]* 2.0f ; 595if (std::memcmp (& expected ,& got [(size_t )i + 1 ],sizeof (float ))!= 0 )++ mismatches ; 596 } 597if (got .front ()!= -12345.0f || got .back ()!= -12345.0f )++ guards ; 598check (DPCT_CHECK_ERROR (delete (exec )), 599"embedding exec destroy" ); 600check (DPCT_CHECK_ERROR (delete (graph )), 601"embedding graph destroy" ); 602 } 603 } 604 } 605 sycl::free (dc , dpct::get_in_order_queue ()); 606 sycl::free (ds , dpct::get_in_order_queue ()); 607 sycl::free (dof , dpct::get_in_order_queue ()); 608 sycl::free (out , dpct::get_in_order_queue ()); 609 } 610 } 611 } 612check ( 613DPCT_CHECK_ERROR (dpct::get_current_device ().destroy_queue (stream )), 614"embedding stream destroy" ); 615 std::printf (" embedding gather: %d row cases, %d bit mismatches, %d guard failures, %d FMA differences\n" , 616cases ,mismatches ,guards ,fma_diff ); 617if (mismatches || guards || fma_diff == 0 )++ bad ; 618 } 619 620// ---- THE f32 -> bf16 CONVERSIONS KEEP A NaN A NaN. `f32_to_bf16_bulk` (the header's `bf16_from_f32` 621// on the device) and the prompt path's dequantizer (its own `f2bf`) against ggml_compute_fp32_to_bf16's rule; 622// before the fix 0x7FFFFFFF came back as -0 and 0x7F800001 as +inf. `bf16_bits_test` covers every f32 on 623// the host; this is the same header compiled by nvcc, plus the second copy in dequant_bf16.cu. 624 { 625auto ggml_bf16 = [](uint32_t u )-> uint16_t { 626if ((u & 0x7fffffffu )> 0x7f800000u )return (uint16_t ) ((u >>16 ) |64 ); 627return (uint16_t ) ((u + (0x7fffu + ((u >>16 )& 1u ))) >>16 ); 628 }; 629 std::vector < uint32_t > bits = {0x7FFFFFFFu ,0xFFFFFFFFu ,0x7F800001u ,0xFF800001u ,0x7FC00000u ,0x7FBFFFFFu , 6300x7F800000u ,0xFF800000u ,0x7F7FFFFFu ,0x00000000u ,0x80000000u ,0x3F808000u , 6310x3F818000u ,0x00008000u ,0x7F7F8000u }; 632 std::mt19937 rng (13 ); 633while (bits .size ()< 4096 )bits .push_back ((uint32_t )rng ()); 634const size_t n = bits .size (); 635float * dx = nullptr ; 636uint16_t * dy = nullptr ; 637check (DPCT_CHECK_ERROR (dx = (float * )sycl::malloc_device ( 638n * 4 , dpct::get_in_order_queue ())), 639"bf16 x" ); 640check (DPCT_CHECK_ERROR (dy = (uint16_t * )sycl::malloc_device ( 641n * 2 , dpct::get_in_order_queue ())), 642"bf16 y" ); 643/* 644DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, 645assuming in the original code the source host memory is pageable memory. 646If the memory is not pageable, call wait() on event return by memcpy API 647to ensure synchronization behavior. 648*/ 649check (DPCT_CHECK_ERROR ( 650 (dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy (dx ,bits .data (),n * 4 ).wait ()), 651"bf16 cx" ); 652 strata::kernels::f32_to_bf16_bulk (dx ,dy , (int64_t )n ,nullptr ); 653 std::vector < uint16_t > got (n ); 654check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()) 655 .memcpy (got .data (),dy ,n * 2 ) 656 .wait ()), 657"bf16 cy" ); 658int wrong = 0 ; 659for (size_t i = 0 ;i < n ;++ i )wrong += got [i ]!= ggml_bf16 (bits [i ]); 660 661// A Q8_0 block (type 8) whose fp16 scale is a NaN: every dequantized value is NaN * q, a NaN, and it must 662// still be one in BF16. A second block with an ordinary scale checks the finite path did not move. 663 std::vector < uint8_t > blk (2 * 34 ,0 ); 664blk [0 ]= 0x00 ;blk [1 ]= 0x7E ;// fp16 quiet NaN 665blk [34 ]= 0x00 ;blk [35 ]= 0x3C ;// fp16 1.0 666for (int j = 0 ;j < 32 ;++ j ) { 667blk [(size_t ) (2 + j )]= (uint8_t ) (int8_t ) (j - 16 ); 668blk [(size_t ) (36 + j )]= (uint8_t ) (int8_t ) (3 * j - 50 ); 669 } 670uint8_t * db = nullptr ; 671uint16_t * dq = nullptr ; 672check (DPCT_CHECK_ERROR (db = (uint8_t * )sycl::malloc_device ( 673blk .size (), dpct::get_in_order_queue ())), 674"q8 blk" ); 675check (DPCT_CHECK_ERROR (dq = (uint16_t * )sycl::malloc_device ( 67664 * 2 , dpct::get_in_order_queue ())), 677"q8 out" ); 678/* 679DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, 680assuming in the original code the source host memory is pageable memory. 681If the memory is not pageable, call wait() on event return by memcpy API 682to ensure synchronization behavior. 683*/ 684check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy (db ,blk .data (), 685blk .size ()).wait ()), 686"q8 cblk" ); 687 strata::kernels::dequant_bf16 (8 ,db ,0 ,2 ,32 ,dq ,nullptr ); 688check (DPCT_CHECK_ERROR ( 689 dpct::get_current_device ().queues_wait_and_throw ()), 690"dequant_bf16" ); 691 std::vector < uint16_t > q (64 ); 692check ( 693DPCT_CHECK_ERROR ( 694 (dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy (q .data (),dq ,64 * 2 ).wait ()), 695"q8 cout" ); 696int dq_wrong = 0 ; 697for (int j = 0 ;j < 32 ;++ j ) { 698if (!((q [(size_t )j ]& 0x7FFFu )> 0x7F80u ))++ dq_wrong ;// row 0: NaN scale -> NaN 699const float v = (float ) (3 * j - 50 );// row 1: d = 1.0 -> the integer 700uint32_t vb ; 701 std::memcpy (& vb ,& v ,4 ); 702if (q [(size_t ) (32 + j )]!= ggml_bf16 (vb ))++ dq_wrong ; 703 } 704 std::printf (" f32 -> bf16 (NaN kept): bulk %d of %zu differ from ggml, dequant_bf16 %d of 64 wrong\n" , 705wrong ,n ,dq_wrong ); 706if (wrong || dq_wrong )++ bad ; 707 sycl::free (dx , dpct::get_in_order_queue ()); 708 sycl::free (dy , dpct::get_in_order_queue ()); 709 sycl::free (db , dpct::get_in_order_queue ()); 710 sycl::free (dq , dpct::get_in_order_queue ()); 711 } 712 713 std::printf ("\nelementwise: %d failures\n" ,bad ); 714if (bad )return 1 ; 715if (selftest ) std::printf ("elementwise_parity OK\n" ); 716return 0 ; 717}