okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
e2b0cbcde
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#include "strata/kernels/dequant_bf16.hpp" 16#include "strata/kernels/elementwise.hpp" 17#include "strata/kernels/f16_bits.hpp" 18 19#include <cuda_runtime.h> 20 21#include <cmath> 22#include <cstdio> 23#include <cstdlib> 24#include <cstring> 25#include <random> 26#include <string> 27#include <vector> 28 29namespace { 30 31void check (cudaError_t e ,const char * what ) { 32if (e != cudaSuccess ) { 33 std::fprintf (stderr ,"%s: %s\n" ,what ,cudaGetErrorString (e )); 34 std::exit (1 ); 35 } 36} 37 38double rel_l1 (const std::vector < float >& a ,const std::vector < float >& b ) { 39double d = 0 ,m = 0 ; 40for (size_t i = 0 ;i < a .size ();++ i ) { 41d += std::fabs ((double )a [i ]- (double )b [i ]); 42m += std::fabs ((double )a [i ]); 43 } 44return d / (m > 1e-30 ?m :1e-30 ); 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: elementwise_parity [--selftest]\n" );return 2 ; } 54 } 55int bad = 0 ; 56const int64_t H_V = 48 ; 57 58// ---- 1. gdn_gate, with the reference's own softplus 59 { 60const int n = (int )H_V ; 61 std::mt19937 rng (11 ); 62 std::normal_distribution < float > g (0.0f ,1.0f ); 63 std::vector < float > alpha (n ),dt (n ),a (n ),want (n ); 64for (int i = 0 ;i < n ;++ i ) { 65// A MIXTURE THAT ACTUALLY CROSSES THE BRANCH. The first version drew alpha from a normal with 66// sigma 3, so the largest value was about 9 and `softplus` never took its `x > 20` path - the 67// "branch is observable" check then reported **0.00% apart, 0 non-finite**, which is the fixture 68// saying it cannot see the thing it was written to see. Every third head is now large. 69const bool large = (i %3 )== 0 ; 70// Up to ~120, so the fixture spans WELL PAST f32's `exp` overflow at 88. A fixture that stopped 71// at 88 would show the branch as unobservable and would be right: `log1pf(expf(x))` equals `x` to 72// f32 precision for the whole range 20..88, so ggml's threshold of 20 is CONSERVATIVE and the 73// behaviour only actually changes where `expf` overflows. 74alpha [i ]= large ? (22.0f + 6.0f * (float ) (i %17 )) :g (rng )* 3.0f ; 75dt [i ]= g (rng )* 0.5f ; 76// NEGATIVE, as the artifact's `ssm_a = -exp(A_log)` is. Checked below as a property. 77a [i ]= - (std::fabs (g (rng ))+ 0.1f ); 78const double x = (double )alpha [i ]+ (double )dt [i ]; 79const double sp = x > 20.0 ?x : std::log1p (std::exp (x )); 80want [(size_t )i ]= (float ) (sp * (double )a [i ]); 81 } 82// the fixture must EXERCISE the branch, or check 1 below measures nothing 83 { 84int over = 0 ,past_overflow = 0 ; 85for (int i = 0 ;i < n ;++ i ) { 86const float x = alpha [(size_t )i ]+ dt [(size_t )i ]; 87if (x > 20.0f )++ over ; 88if (x > 88.0f )++ past_overflow ; 89 } 90 std::printf (" %-44s %s (%d above 20, %d above 88)\n" ,"the fixture crosses the branch" , 91over ?"yes" :"*** NO ***" ,over ,past_overflow ); 92if (!over )++ bad ; 93 } 94// the sign property, asserted rather than assumed 95int positive = 0 ; 96for (int i = 0 ;i < n ;++ i )if (a [(size_t )i ] >=0.0f )++ positive ; 97 std::printf (" %-44s %s (%d of %d non-negative)\n" ,"the fixture's ssm_a is negative" , 98positive ?"*** NO ***" :"yes" ,positive ,n ); 99if (positive )++ bad ; 100 101float * d_a = nullptr ,* d_dt = nullptr ,* d_sa = nullptr ,* d_g = nullptr ; 102check (cudaMalloc (& d_a ,n * 4 ),"a" ); 103check (cudaMalloc (& d_dt ,n * 4 ),"dt" ); 104check (cudaMalloc (& d_sa ,n * 4 ),"sa" ); 105check (cudaMalloc (& d_g ,n * 4 ),"g" ); 106check (cudaMemcpy (d_a ,alpha .data (),n * 4 ,cudaMemcpyHostToDevice ),"ca" ); 107check (cudaMemcpy (d_dt ,dt .data (),n * 4 ,cudaMemcpyHostToDevice ),"cd" ); 108check (cudaMemcpy (d_sa ,a .data (),n * 4 ,cudaMemcpyHostToDevice ),"cs" ); 109 strata::kernels::gdn_gate (d_a ,d_dt ,d_sa ,d_g ,1 ,H_V ,nullptr ); 110 std::vector < float > got ((size_t )n ); 111check (cudaMemcpy (got .data (),d_g ,n * 4 ,cudaMemcpyDeviceToHost ),"cg" ); 112 113const double rel = rel_l1 (want ,got ); 114 std::printf (" %-44s rel %.3e\n" ,"gdn_gate vs the reference" ,rel ); 115// double softplus and double multiply on both sides, then one cast 116if (!(rel <=1e-6 )) { std::printf (" *** over 1e-6 ***\n" );++ bad ; } 117 118// TRAP: no large-x branch. `log1p(exp(x))` in f32, with no `x > 20` path. 119// 120// AND THE MEASUREMENT SAYS WHERE THE BRANCH ACTUALLY MATTERS. The first version of this fixture 121// spanned 20..88 and reported **0 heads differ**: `log1pf(expf(x))` agrees with `x` to f32 precision 122// over that whole range, so ggml's threshold of 20 is CONSERVATIVE - the branch changes the answer only 123// where `expf` OVERFLOWS, at about 88. The check reports the smallest x at which the two readings 124// part company, so the number is in the output rather than in this comment. 125 { 126int wrong = 0 ,differing = 0 ; 127float first_differ = -1.0f ; 128 std::vector < float > rival ((size_t )n ); 129for (int i = 0 ;i < n ;++ i ) { 130const float x = alpha [(size_t )i ]+ dt [(size_t )i ]; 131const float sp = std::log1p (std::exp (x ));// no branch, f32 132rival [(size_t )i ]= sp * a [(size_t )i ]; 133if (!std::isfinite (sp ))++ wrong ; 134const float branched = x > 20.0f ?x : std::log1pf (std::exp (x )); 135if (sp != branched ) { 136++ differing ; 137if (first_differ < 0.0f || x < first_differ )first_differ = x ; 138 } 139 } 140const double r = rel_l1 (want ,rival ); 141const bool visible = r > 0.05 || wrong > 0 ; 142 std::printf (" %-44s %s (%.2f%% apart, %d non-finite, %d heads differ, first at x = %.1f)\n" , 143"the softplus large-x branch is observable" ,visible ?"yes" :"*** NO ***" , 144r * 100 ,wrong ,differing , (double )first_differ ); 145if (!visible )++ bad ; 146 } 147// PROPERTY: exp(gate) < 1 for every element, which is what makes the state decay 148 { 149int over = 0 ; 150for (float v :got )if (!(std::exp (v )< 1.0f ))++ over ; 151 std::printf (" %-44s %s (%d of %d not < 1)\n" ,"exp(gate) < 1 for every head" , 152over ?"*** NO ***" :"yes" ,over ,n ); 153if (over )++ bad ; 154 } 155cudaFree (d_a );cudaFree (d_dt );cudaFree (d_sa );cudaFree (d_g ); 156 } 157 158// ---- 2. silu, in double then cast 159 { 160const int n = 4096 ; 161 std::mt19937 rng (22 ); 162 std::normal_distribution < float > g (0.0f ,3.0f ); 163 std::vector < float > x ((size_t )n ),want ((size_t )n ); 164for (int i = 0 ;i < n ;++ i ) { 165x [(size_t )i ]= g (rng ); 166const double v = (double )x [(size_t )i ]; 167want [(size_t )i ]= (float ) (v / (1.0 + std::exp (- v ))); 168 } 169float * d_x = nullptr ; 170check (cudaMalloc (& d_x ,n * 4 ),"sx" ); 171check (cudaMemcpy (d_x ,x .data (),n * 4 ,cudaMemcpyHostToDevice ),"csx" ); 172 strata::kernels::silu_inplace (d_x ,n ,nullptr ); 173 std::vector < float > got ((size_t )n ); 174check (cudaMemcpy (got .data (),d_x ,n * 4 ,cudaMemcpyDeviceToHost ),"csg" ); 175const double rel = rel_l1 (want ,got ); 176 std::printf ("\n %-44s rel %.3e\n" ,"silu (double) vs the reference" ,rel ); 177if (!(rel <=1e-7 )) { std::printf (" *** over 1e-7 ***\n" );++ bad ; } 178cudaFree (d_x ); 179 } 180 181// ---- 3. scale and the f32->f16 bridge 182 { 183const int n = 1024 ; 184 std::vector < float > x ((size_t )n ),want ((size_t )n ); 185for (int i = 0 ;i < n ;++ i )x [(size_t )i ]= (float ) (i - n /2 )* 0.013f ; 186const float s = 1.0f / std::sqrt (128.0f ); 187for (int i = 0 ;i < n ;++ i )want [(size_t )i ]= x [(size_t )i ]* s ; 188 189float * d_x = nullptr ; 190uint16_t * d_h = nullptr ; 191check (cudaMalloc (& d_x ,n * 4 ),"ex" ); 192check (cudaMalloc (& d_h ,n * 2 ),"eh" ); 193check (cudaMemcpy (d_x ,x .data (),n * 4 ,cudaMemcpyHostToDevice ),"cex" ); 194 strata::kernels::scale_inplace (d_x ,n ,s ,nullptr ); 195 std::vector < float > got ((size_t )n ); 196check (cudaMemcpy (got .data (),d_x ,n * 4 ,cudaMemcpyDeviceToHost ),"ceg" ); 197int diff = 0 ; 198for (int i = 0 ;i < n ;++ i )if (got [(size_t )i ]!= want [(size_t )i ])++ diff ; 199 std::printf (" %-44s %d of %d differ\n" ,"scale_inplace is exact" ,diff ,n ); 200if (diff )++ bad ; 201 202 strata::kernels::f32_to_f16_bulk (d_x ,d_h ,n ,nullptr ); 203 std::vector < uint16_t > h ((size_t )n ); 204check (cudaMemcpy (h .data (),d_h ,n * 2 ,cudaMemcpyDeviceToHost ),"ceh" ); 205int hbad = 0 ; 206for (int i = 0 ;i < n ;++ i ) 207if (h [(size_t )i ]!= strata::kernels::f16_from_f32 (got [(size_t )i ]))++ hbad ; 208 std::printf (" %-44s %d of %d differ\n" ,"f32_to_f16_bulk uses the shared conversion" ,hbad ,n ); 209if (hbad )++ bad ; 210cudaFree (d_x );cudaFree (d_h ); 211 } 212 213// ---- 4. rms_norm_weighted, and the TWO RIVAL READINGS it exists to be told apart from. 214// 215// This kernel's whole reason for being a separate entry point from `gdn_l2_norm` is that the two differ by 216// one `/ cols`, and that a swap produces a well-scaled, plausible tensor. So the test computes BOTH wrong 217// readings and requires each to differ from the right one by more than the tolerance before it judges the 218// kernel - the same discipline the shared-expert test uses for silu-on-gate. 219 { 220const int64_t rows = 24 ,cols = 256 ;// the real `attn_q`-norm shape 221const float eps = 1e-6f ; 222 std::vector < float > x ((size_t ) (rows * cols )); 223for (size_t i = 0 ;i < x .size ();++ i )x [i ]= (float ) std::sin ((double )i * 0.017 )* 1.7f + 0.4f ; 224 std::vector < float > w ((size_t )cols ); 225for (int64_t c = 0 ;c < cols ;++ c )w [(size_t )c ]= 0.5f + 0.002f * (float ) (c %97 ); 226 227// the oracle: f64, mean, times w 228auto ref = [& ](bool use_sum ,bool use_w ) { 229 std::vector < double > y ((size_t ) (rows * cols )); 230for (int64_t r = 0 ;r < rows ;++ r ) { 231double ss = 0 ; 232for (int64_t c = 0 ;c < cols ;++ c ) { 233const double v = x [(size_t ) (r * cols + c )]; 234ss += v * v ; 235 } 236const double den = std::sqrt ((use_sum ?ss :ss / (double )cols )+ (double )eps ); 237for (int64_t c = 0 ;c < cols ;++ c ) { 238const double v = x [(size_t ) (r * cols + c )]; 239y [(size_t ) (r * cols + c )]= (v /den )* (use_w ? (double )w [(size_t )c ] :1.0 ); 240 } 241 } 242 std::vector < float > out ((size_t ) (rows * cols )); 243for (size_t i = 0 ;i < out .size ();++ i )out [i ]= (float )y [i ]; 244return out ; 245 }; 246const std::vector < float > want = ref (false, true); 247const std::vector < float > rival_sum = ref (true, false);// what gdn_l2_norm computes 248const std::vector < float > rival_now = ref (false, false);// the (1+w)-vs-w / no-weight confusion 249 250auto rel = [& ](const std::vector < float >& a ,const std::vector < float >& b ) { 251double d = 0 ,m = 0 ; 252for (size_t i = 0 ;i < a .size ();++ i ) { 253d += std::fabs ((double )a [i ]- (double )b [i ]); 254m += std::fabs ((double )a [i ]); 255 } 256return d / (m > 1e-30 ?m :1e-30 ); 257 }; 258const double r_sum = rel (want ,rival_sum ),r_now = rel (want ,rival_now ); 259 std::printf (" %-44s %.2f%% apart\n" ,"sum-vs-mean is observable" ,r_sum * 100 ); 260 std::printf (" %-44s %.2f%% apart\n" ,"with-w-vs-without-w is observable" ,r_now * 100 ); 261// `sqrt(cols)` = 16 for the first and the weight's own spread for the second; a fixture that cannot 262// separate them is not testing the kernel that was written. 263if (!(r_sum > 0.5 )) { std::printf (" *** the sum reading is NOT observable ***\n" );++ bad ; } 264if (!(r_now > 0.5 )) { std::printf (" *** the no-weight reading is NOT observable ***\n" );++ bad ; } 265 266float * d_x = nullptr ; 267float * d_w = nullptr ; 268check (cudaMalloc (& d_x ,x .size ()* 4 ),"m rmsx" ); 269check (cudaMalloc (& d_w ,w .size ()* 4 ),"m rmsw" ); 270check (cudaMemcpy (d_x ,x .data (),x .size ()* 4 ,cudaMemcpyHostToDevice ),"c rmsx" ); 271check (cudaMemcpy (d_w ,w .data (),w .size ()* 4 ,cudaMemcpyHostToDevice ),"c rmsw" ); 272 strata::kernels::rms_norm_weighted (d_x ,d_w ,rows ,cols ,eps ,nullptr ); 273 std::vector < float > got ((size_t ) (rows * cols )); 274check (cudaMemcpy (got .data (),d_x ,got .size ()* 4 ,cudaMemcpyDeviceToHost ),"c rmsg" ); 275 276const double r_got = rel (want ,got ); 277double worst = 0 ; 278for (size_t i = 0 ;i < got .size ();++ i ) { 279const double m = std::fabs ((double )want [i ]); 280const double e = std::fabs ((double )got [i ]- (double )want [i ]) / (m > 1e-30 ?m :1e-30 ); 281if (e > worst )worst = e ; 282 } 283int nonfinite = 0 ; 284for (float v :got )if (!std::isfinite (v ))++ nonfinite ; 285 std::printf (" %-44s rel %.3e worst %.3e nonfinite %d\n" ,"rms_norm_weighted vs f64 oracle" ,r_got , 286worst ,nonfinite ); 287if (nonfinite )++ bad ; 288// The kernel accumulates in f32 over 256 terms; 1e-6 is loose enough for that and far tighter than the 289// 16x the rival readings are off by. 290if (!(r_got < 1e-6 )) { std::printf (" *** rms_norm_weighted is WRONG ***\n" );++ bad ; } 291// and a null `w` must be legal, because `ref/qsa.py` allows it. 292// 293// THE INPUT HAS TO BE RE-UPLOADED FIRST. The kernel is IN PLACE, so `d_x` currently holds the 294// NORMALISED tensor from the call above; running it again normalises a second time and every element 295// differs. That is exactly what the first version of this check reported - "6144 of 6144 differ" - 296// and it is a fixture bug rather than a kernel bug: the oracle reads the ORIGINAL `x`, so the two 297// sides were never looking at the same input. 298const std::vector < float > want_null = ref (false, false); 299check (cudaMemcpy (d_x ,x .data (),x .size ()* 4 ,cudaMemcpyHostToDevice ),"c rmsx2" ); 300 strata::kernels::rms_norm_weighted (d_x ,nullptr ,rows ,cols ,eps ,nullptr ); 301check (cudaMemcpy (got .data (),d_x ,got .size ()* 4 ,cudaMemcpyDeviceToHost ),"c rmsn" ); 302int null_bad = 0 ; 303for (size_t i = 0 ;i < got .size ();++ i ) 304if (std::fabs ((double )got [i ]- (double )want_null [i ])> 1e-6 )++ null_bad ; 305 std::printf (" %-44s %d of %zu differ\n" ,"a null weight is legal" ,null_bad ,got .size ()); 306if (null_bad )++ bad ; 307cudaFree (d_x ); 308cudaFree (d_w ); 309 } 310 311// Packed embedding rows: every code width, scale-group size, optional offset, 312// row boundary and partial CUDA block. Compare bits with a scalar CPU decoder. 313// Volatile materializes the multiply so this oracle cannot silently use FMA. 314 { 315cudaStream_t stream ; 316check (cudaStreamCreateWithFlags (& stream ,cudaStreamNonBlocking ),"embedding stream" ); 317 std::mt19937 rng (77 ); 318 std::uniform_real_distribution < float > values (-2.0f ,2.0f ); 319int mismatches = 0 ,guards = 0 ,fma_diff = 0 ,cases = 0 ; 320for (const int bits : {2 ,4 ,8 }) { 321const int bias = bits == 2 ?-1 :bits == 4 ?-7 :-16 ; 322const int per_byte = 8 /bits ; 323const unsigned mask = (1u <<bits )- 1u ; 324for (const int group : {16 ,32 ,64 }) { 325for (const int n : {320 ,2560 }) { 326const int row_bytes = n /per_byte ,row_groups = n /group ; 327 std::vector < uint8_t > codes ((size_t )3 * row_bytes ,0 ); 328 std::vector < float > scales ((size_t )3 * row_groups ),offsets (scales .size ()); 329 std::vector < int > unpacked ((size_t )3 * n ); 330for (size_t i = 0 ;i < unpacked .size ();++ i ) { 331const unsigned code = (unsigned ) (i * 13 + i /n * 7 )& mask ; 332unpacked [i ]= (int )code ; 333codes [i /per_byte ] |= (uint8_t ) (code << ((i %per_byte )* bits )); 334 } 335for (size_t i = 0 ;i < scales .size ();++ i ) { 336scales [i ]= values (rng ); 337offsets [i ]= values (rng ); 338 } 339scales [0 ]= -0.0f ; 340offsets [0 ]= 0.0f ; 341uint8_t * dc = nullptr ; 342float * ds = nullptr ,* dof = nullptr ,* out = nullptr ; 343check (cudaMalloc (& dc ,codes .size ()),"embedding codes" ); 344check (cudaMalloc (& ds ,scales .size ()* sizeof (float )),"embedding scales" ); 345check (cudaMalloc (& dof ,offsets .size ()* sizeof (float )),"embedding offsets" ); 346check (cudaMalloc (& out , ((size_t )n + 2 )* sizeof (float )),"embedding output" ); 347check (cudaMemcpyAsync (dc ,codes .data (),codes .size (),cudaMemcpyHostToDevice ,stream ),"embedding codes upload" ); 348check (cudaMemcpyAsync (ds ,scales .data (),scales .size ()* sizeof (float ),cudaMemcpyHostToDevice ,stream ),"embedding scales upload" ); 349check (cudaMemcpyAsync (dof ,offsets .data (),offsets .size ()* sizeof (float ),cudaMemcpyHostToDevice ,stream ),"embedding offsets upload" ); 350check (cudaStreamSynchronize (stream ),"embedding upload sync" ); 351 352for (const bool with_offset : {false, true}) { 353for (int row = 0 ;row < 3 ;++ row ) { 354 std::vector < float > want ((size_t )n ),got ((size_t )n + 2 ,-12345.0f ); 355for (int i = 0 ;i < n ;++ i ) { 356const size_t gi = (size_t )row * row_groups + i /group ; 357const float code = (float ) (unpacked [(size_t )row * n + i ]+ bias ); 358volatile float product = code * scales [gi ]; 359const float offset = with_offset ?offsets [gi ] :0.0f ; 360want [(size_t )i ]= product + offset ; 361const float fused = std::fma (code ,scales [gi ],offset ); 362if (std::memcmp (& fused ,& want [(size_t )i ],sizeof (float ))!= 0 )++ fma_diff ; 363 } 364check (cudaMemcpyAsync (out ,got .data (),got .size ()* sizeof (float ),cudaMemcpyHostToDevice ,stream ),"embedding output guards" ); 365 strata::kernels::embedding_gather (dc + (size_t )row * row_bytes , 366ds + (size_t )row * row_groups , 367with_offset ?dof + (size_t )row * row_groups :nullptr , 368n ,bits ,bias ,group ,out + 1 ,stream ); 369check (cudaMemcpyAsync (got .data (),out ,got .size ()* sizeof (float ),cudaMemcpyDeviceToHost ,stream ),"embedding result" ); 370check (cudaStreamSynchronize (stream ),"embedding sync" ); 371for (int i = 0 ;i < n ;++ i ) { 372if (std::memcmp (& want [(size_t )i ],& got [(size_t )i + 1 ],sizeof (float ))!= 0 )++ mismatches ; 373 } 374if (got .front ()!= -12345.0f || got .back ()!= -12345.0f )++ guards ; 375++ cases ; 376 377// Capturing the gather proves that it has no hidden synchronization. 378// A following scale also checks that it uses the caller's stream. 379if (row == 1 ) { 380cudaGraph_t graph ; 381cudaGraphExec_t exec ; 382check (cudaStreamBeginCapture (stream ,cudaStreamCaptureModeThreadLocal ),"embedding capture" ); 383 strata::kernels::embedding_gather (dc + (size_t )row * row_bytes , 384ds + (size_t )row * row_groups , 385with_offset ?dof + (size_t )row * row_groups :nullptr , 386n ,bits ,bias ,group ,out + 1 ,stream ); 387 strata::kernels::scale_inplace (out + 1 ,n ,2.0f ,stream ); 388check (cudaStreamEndCapture (stream ,& graph ),"embedding capture end" ); 389check (cudaGraphInstantiate (& exec ,graph ,0 ),"embedding instantiate" ); 390check (cudaGraphLaunch (exec ,stream ),"embedding replay" ); 391check (cudaMemcpyAsync (got .data (),out ,got .size ()* sizeof (float ),cudaMemcpyDeviceToHost ,stream ),"embedding graph result" ); 392check (cudaStreamSynchronize (stream ),"embedding graph sync" ); 393for (int i = 0 ;i < n ;++ i ) { 394const float expected = want [(size_t )i ]* 2.0f ; 395if (std::memcmp (& expected ,& got [(size_t )i + 1 ],sizeof (float ))!= 0 )++ mismatches ; 396 } 397if (got .front ()!= -12345.0f || got .back ()!= -12345.0f )++ guards ; 398check (cudaGraphExecDestroy (exec ),"embedding exec destroy" ); 399check (cudaGraphDestroy (graph ),"embedding graph destroy" ); 400 } 401 } 402 } 403cudaFree (dc );cudaFree (ds );cudaFree (dof );cudaFree (out ); 404 } 405 } 406 } 407check (cudaStreamDestroy (stream ),"embedding stream destroy" ); 408 std::printf (" embedding gather: %d row cases, %d bit mismatches, %d guard failures, %d FMA differences\n" , 409cases ,mismatches ,guards ,fma_diff ); 410if (mismatches || guards || fma_diff == 0 )++ bad ; 411 } 412 413// ---- THE f32 -> bf16 CONVERSIONS KEEP A NaN A NaN. `f32_to_bf16_bulk` (the header's `bf16_from_f32` 414// on the device) and the prompt path's dequantizer (its own `f2bf`) against ggml_compute_fp32_to_bf16's rule; 415// before the fix 0x7FFFFFFF came back as -0 and 0x7F800001 as +inf. `bf16_bits_test` covers every f32 on 416// the host; this is the same header compiled by nvcc, plus the second copy in dequant_bf16.cu. 417 { 418auto ggml_bf16 = [](uint32_t u )-> uint16_t { 419if ((u & 0x7fffffffu )> 0x7f800000u )return (uint16_t ) ((u >>16 ) |64 ); 420return (uint16_t ) ((u + (0x7fffu + ((u >>16 )& 1u ))) >>16 ); 421 }; 422 std::vector < uint32_t > bits = {0x7FFFFFFFu ,0xFFFFFFFFu ,0x7F800001u ,0xFF800001u ,0x7FC00000u ,0x7FBFFFFFu , 4230x7F800000u ,0xFF800000u ,0x7F7FFFFFu ,0x00000000u ,0x80000000u ,0x3F808000u , 4240x3F818000u ,0x00008000u ,0x7F7F8000u }; 425 std::mt19937 rng (13 ); 426while (bits .size ()< 4096 )bits .push_back ((uint32_t )rng ()); 427const size_t n = bits .size (); 428float * dx = nullptr ; 429uint16_t * dy = nullptr ; 430check (cudaMalloc (& dx ,n * 4 ),"bf16 x" ); 431check (cudaMalloc (& dy ,n * 2 ),"bf16 y" ); 432check (cudaMemcpy (dx ,bits .data (),n * 4 ,cudaMemcpyHostToDevice ),"bf16 cx" ); 433 strata::kernels::f32_to_bf16_bulk (dx ,dy , (int64_t )n ,nullptr ); 434 std::vector < uint16_t > got (n ); 435check (cudaMemcpy (got .data (),dy ,n * 2 ,cudaMemcpyDeviceToHost ),"bf16 cy" ); 436int wrong = 0 ; 437for (size_t i = 0 ;i < n ;++ i )wrong += got [i ]!= ggml_bf16 (bits [i ]); 438 439// A Q8_0 block (type 8) whose fp16 scale is a NaN: every dequantized value is NaN * q, a NaN, and it must 440// still be one in BF16. A second block with an ordinary scale checks the finite path did not move. 441 std::vector < uint8_t > blk (2 * 34 ,0 ); 442blk [0 ]= 0x00 ;blk [1 ]= 0x7E ;// fp16 quiet NaN 443blk [34 ]= 0x00 ;blk [35 ]= 0x3C ;// fp16 1.0 444for (int j = 0 ;j < 32 ;++ j ) { 445blk [(size_t ) (2 + j )]= (uint8_t ) (int8_t ) (j - 16 ); 446blk [(size_t ) (36 + j )]= (uint8_t ) (int8_t ) (3 * j - 50 ); 447 } 448uint8_t * db = nullptr ; 449uint16_t * dq = nullptr ; 450check (cudaMalloc (& db ,blk .size ()),"q8 blk" ); 451check (cudaMalloc (& dq ,64 * 2 ),"q8 out" ); 452check (cudaMemcpy (db ,blk .data (),blk .size (),cudaMemcpyHostToDevice ),"q8 cblk" ); 453 strata::kernels::dequant_bf16 (8 ,db ,0 ,2 ,32 ,dq ,nullptr ); 454check (cudaDeviceSynchronize (),"dequant_bf16" ); 455 std::vector < uint16_t > q (64 ); 456check (cudaMemcpy (q .data (),dq ,64 * 2 ,cudaMemcpyDeviceToHost ),"q8 cout" ); 457int dq_wrong = 0 ; 458for (int j = 0 ;j < 32 ;++ j ) { 459if (!((q [(size_t )j ]& 0x7FFFu )> 0x7F80u ))++ dq_wrong ;// row 0: NaN scale -> NaN 460const float v = (float ) (3 * j - 50 );// row 1: d = 1.0 -> the integer 461uint32_t vb ; 462 std::memcpy (& vb ,& v ,4 ); 463if (q [(size_t ) (32 + j )]!= ggml_bf16 (vb ))++ dq_wrong ; 464 } 465 std::printf (" f32 -> bf16 (NaN kept): bulk %d of %zu differ from ggml, dequant_bf16 %d of 64 wrong\n" , 466wrong ,n ,dq_wrong ); 467if (wrong || dq_wrong )++ bad ; 468cudaFree (dx );cudaFree (dy );cudaFree (db );cudaFree (dq ); 469 } 470 471 std::printf ("\nelementwise: %d failures\n" ,bad ); 472if (bad )return 1 ; 473if (selftest ) std::printf ("elementwise_parity OK\n" ); 474return 0 ; 475}