okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
db137d917
main
1// src/kernels/native_grouped_parity.cpp - native_expert_grouped's group stride (grid_groups) and its fused SwiGLU + 2// q8_1 pass, against the launches before them (native_grouped_set_v1: a block row per possible group, SwiGLU and the 3// q8_1 quantization as two kernels over all cap_entries). Synthetic blobs, no model. 4// 5// build/native_grouped_parity the checks (a ctest; needs the GPU) 6// build/native_grouped_parity --bench the checks, then v1/new timings of 48 calls in a graph (a window's layers) 7// 8// Every gate/up format with every down format; calls of 0..cap groups of 1..T entries each (an empty call is what the 9// verify window's PCIe call usually is), entries from 0 and from past 0 (the PCIe call's follow the VRAM call's), 10// scattered destinations, stale scratch, grid_groups 0 (= cap), 1, 2, 3, 4 and above cap: the output must be BITWISE 11// equal to v1's, the rows the call must not write included (both start from the same NaN pattern). 12// 13// Random bytes are valid codes for every format here (every grid index is in range); only the fp16 block scales are 14// set, small enough that the SwiGLU outputs keep a finite fp16 q8_1 scale. 15#define DPCT_PROFILING_ENABLED 16#include <sycl/sycl.hpp> 17#include <dpct/dpct.hpp> 18#include "strata/kernels/iq_kernels.hpp" 19#include "strata/core/geometry.hpp" 20 21#include <algorithm> 22#include <cmath> 23#include <cstdio> 24#include <cstdlib> 25#include <cstring> 26#include <numeric> 27#include <random> 28#include <string> 29#include <vector> 30 31namespace strata::kernels { 32// SYCL port only (iq_kernels.dp.cpp): the K-quant / Q5_1 / Q8_0 lane kernels with (true, the default) or without the 33// multi-entry split; STRATA_KQ_SPLIT=0 at startup is false 34void native_expert_set_kq_split (bool on ); 35} 36namespace k= strata::kernels; 37 38namespace { 39 40int g_fail = 0 ; 41 42void ck (dpct::err0 e ,const char * what ) { 43} 44 45template < typename T > 46T * dalloc (size_t n ) { 47T * p = nullptr ; 48ck (DPCT_CHECK_ERROR (p = (T * )sycl::malloc_device ( 49n * sizeof (T )+ 256 , dpct::get_in_order_queue ())), 50"malloc" ); 51ck (DPCT_CHECK_ERROR ( 52 (dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memset (p ,0 ,n * sizeof (T )+ 256 ).wait ()), 53"memset" ); 54return p ; 55} 56 57const char * name_of (int t ) { 58switch (t ) { 59case 16 :return "IQ2_XXS" ; 60case 17 :return "IQ2_XS" ; 61case 18 :return "IQ3_XXS" ; 62case 20 :return "IQ4_NL" ; 63case 21 :return "IQ3_S" ; 64case 22 :return "IQ2_S" ; 65case 23 :return "IQ4_XS" ; 66case 29 :return "IQ1_M" ; 67case 42 :return "Q2_0" ; 68case 12 :return "Q4_K" ; 69case 13 :return "Q5_K" ; 70case 14 :return "Q6_K" ; 71case 7 :return "Q5_1" ; 72case 8 :return "Q8_0" ; 73default :return "?" ; 74 } 75} 76int block_values (int t ) {return t == 20 || t == 7 || t == 8 ?32 :t == 42 ?64 :256 ; } 77 78// `rows` rows of `n` values of format t: random bytes, then a finite fp16 scale in every block 79std::vector < uint8_t > random_rows (int t ,int64_t rows ,int64_t n , std::mt19937 & rng ) { 80const size_t rb = k::iq_row_bytes (t ,n ),bs = k::iq_row_bytes (t ,block_values (t )); 81 std::vector < uint8_t > w ((size_t )rows * rb ); 82 std::uniform_int_distribution < int > byte (0 ,255 ),ex (2 ,8 ),man (0 ,1023 ),sgn (0 ,1 ); 83for (auto & b :w )b = (uint8_t )byte (rng ); 84for (size_t o = 0 ;o < w .size ();o += bs ) { 85if (t == 29 ) { 86// IQ1_M: the fp16 scale is the top nibbles of its four scale words (bytes 48..55), the sign and the 87// exponent's top bits in the last: 0x1 / 0x2 there (0x9 / 0xA negative) keeps it in 2^-11 .. 2^-3 88const uint8_t nib = (uint8_t ) ((sgn (rng ) ?0x8 :0x0 ) | (1 + (byte (rng )& 1 ))); 89w [o + 55 ]= (uint8_t ) ((w [o + 55 ]& 0x0F ) | (nib <<4 )); 90 }else {// the other formats start their block with the fp16 scale: 2^-13 .. 2^-6 91// (Q4_K / Q5_K: 2^-14 .. 2^-11, their 6-bit sub-scales multiply it by up to 63) 92const int e = (t == 12 || t == 13 ) ?1 + ex (rng ) %4 :ex (rng ); 93const uint16_t h = (uint16_t ) ((sgn (rng ) ?0x8000 :0 ) | (e <<10 ) |man (rng )); 94 std::memcpy (& w [o + (t == 14 ?208 :0 )],& h ,2 );// Q6_K keeps its fp16 scale last (ql, qh, scales, d) 95if (t == 12 || t == 13 || t == 7 ) {// Q4_K / Q5_K: dmin, Q5_1: m - the second fp16, as small 96const int em = (t == 7 ) ?ex (rng ) :1 + ex (rng ) %4 ; 97const uint16_t m = (uint16_t ) ((sgn (rng ) ?0x8000 :0 ) | (em <<10 ) |man (rng )); 98 std::memcpy (& w [o + 2 ],& m ,2 ); 99 } 100 } 101 } 102return w ; 103} 104 105// one window's worth of expert calls on one format pair: blobs, T tokens' q8_1 activations, cap = T * K entries 106struct Setup { 107 k::NativeExpertLayout L ; 108int T = 0 ,K = 0 ,cap = 0 ,n_blobs = 0 ; 109size_t slot = 0 ; 110uint8_t * blobs = nullptr ; 111uint8_t * xq = nullptr ; 112uint8_t * scr = nullptr ; 113size_t scr_bytes = 0 ; 114float * out = nullptr ; 115size_t out_floats = 0 ; 116unsigned long long * ptr = nullptr ; 117int32_t * start = nullptr ,* n = nullptr ,* dst = nullptr ,* tok = nullptr ; 118 std::vector < std::vector < uint8_t >> hb ;// host copies: the blobs, the q8_1 activations, the last plan 119 std::vector < uint8_t > h_xq ; 120 std::vector < int > h_blob ; 121 std::vector < int32_t > h_start ,h_tok ,h_dst ; 122 123Setup (int gu ,int dt ,int64_t H ,int64_t FF ,int tokens ,int k_per_token , 124int blobs_n , std::mt19937 & rng , dpct::queue_ptr s ) { 125L = k::native_expert_layout (gu ,dt ,H ,FF ); 126T = tokens ;K = k_per_token ;cap = T * K ;n_blobs = blobs_n ; 127slot = (L .bytes + 255 )& ~(size_t )255 ; 128blobs = dalloc < uint8_t > (slot * (size_t )n_blobs ); 129for (int b = 0 ;b < n_blobs ;++ b ) { 130// gate rows | up rows (format gu, H values each) | down rows (format dt, FF values each) 131auto blob = random_rows (gu ,2 * FF ,H ,rng ); 132const auto down = random_rows (dt ,H ,FF ,rng ); 133blob .insert (blob .end (),down .begin (),down .end ()); 134hb .push_back (blob ); 135if (blob .size ()!= L .bytes ) { std::fprintf (stderr ,"blob %zu != %zu bytes\n" ,blob .size (),L .bytes ); std::exit (2 ); } 136/* 137DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, 138assuming in the original code the source host memory is pageable 139memory. If the memory is not pageable, call wait() on event return 140by memcpy API to ensure synchronization behavior. 141*/ 142ck (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy ( 143blobs + slot * (size_t )b ,blob .data (),blob .size ()).wait ()), 144"blob" ); 145 } 146 std::normal_distribution < float > nd (0.f ,1.f ); 147 std::vector < float > x ((size_t )T * H ); 148for (auto & v :x )v = nd (rng ); 149float * dx = dalloc < float > (x .size ()); 150/* 151DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, 152assuming in the original code the source host memory is pageable memory. 153If the memory is not pageable, call wait() on event return by memcpy API 154to ensure synchronization behavior. 155*/ 156ck (DPCT_CHECK_ERROR ( 157 (dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy (dx ,x .data (),x .size ()* 4 ).wait ()), 158"x" ); 159xq = dalloc < uint8_t > ((size_t )T * (H /32 )* 36 ); 160 k::quantize_q8_1_rows (dx ,T ,H ,xq ,s ); 161h_xq .resize ((size_t )T * (H /32 )* 36 ); 162s -> memcpy (h_xq .data (),xq ,h_xq .size ()).wait (); 163ck (DPCT_CHECK_ERROR (s -> wait ()),"quantize" ); 164 sycl::free (dx , dpct::get_in_order_queue ()); 165scr_bytes = k::native_expert_scratch_bytes (cap ,FF ); 166scr = dalloc < uint8_t > (scr_bytes ); 167out_floats = (size_t )cap * H ; 168out = dalloc < float > (out_floats ); 169ptr = dalloc < unsigned long long > (cap ); 170start = dalloc < int32_t > (cap + 1 ); 171n = dalloc < int32_t > (1 ); 172dst = dalloc < int32_t > (cap ); 173tok = dalloc < int32_t > (cap ); 174 } 175 ~Setup () { 176 sycl::free (blobs , dpct::get_in_order_queue ()); 177 sycl::free (xq , dpct::get_in_order_queue ()); 178 sycl::free (scr , dpct::get_in_order_queue ()); 179 sycl::free (out , dpct::get_in_order_queue ()); 180 sycl::free (ptr , dpct::get_in_order_queue ()); 181 sycl::free (start , dpct::get_in_order_queue ()); 182 sycl::free (n , dpct::get_in_order_queue ()); 183 sycl::free (dst , dpct::get_in_order_queue ()); 184 sycl::free (tok , dpct::get_in_order_queue ()); 185 } 186// a plan: `groups` groups of 1..T entries from entry `base` on (as many as fit in cap) 187int plan (int groups ,int base , std::mt19937 & rng ) { 188 std::uniform_int_distribution < int > size (1 ,T ); 189 std::vector < int > sizes ; 190int used = base ; 191for (int g = 0 ;g < groups ;++ g ) { 192const int m = std::min (size (rng ),cap - used ); 193if (m <=0 )break ; 194sizes .push_back (m ); 195used += m ; 196 } 197return plan_sizes (sizes ,base ,rng ); 198 } 199// groups of these sizes from entry `base` on, each its own blob (as long as there are enough: a window's groups 200// are different experts); scattered destinations, random tokens 201int plan_sizes (const std::vector < int >& sizes ,int base , std::mt19937 & rng ) { 202 std::uniform_int_distribution < int > tk (0 ,T - 1 ); 203 std::vector < int > order (n_blobs ); 204 std::iota (order .begin (),order .end (),0 ); 205 std::shuffle (order .begin (),order .end (),rng ); 206 std::vector < unsigned long long > p ; 207 std::vector < int32_t > st (1 ,base ),tk_v ,ds (cap ); 208h_blob .clear (); 209for (const int m :sizes ) { 210h_blob .push_back (order [p .size () %order .size ()]); 211p .push_back ((unsigned long long ) (blobs + slot * (size_t )order [p .size () %order .size ()])); 212st .push_back (st .back ()+ m ); 213 } 214if (st .back ()> cap ) { std::fprintf (stderr ,"plan: %d entries > cap %d\n" ,st .back (),cap ); std::exit (2 ); } 215const int ng = (int )p .size (); 216 std::iota (ds .begin (),ds .end (),0 ); 217 std::shuffle (ds .begin (),ds .end (),rng );// scattered rows of `out` 218for (int e = 0 ;e < cap ;++ e )tk_v .push_back (tk (rng )); 219h_start = st ;h_tok = tk_v ;h_dst = ds ;// host copies for the CPU reference 220/* 221DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, 222assuming in the original code the source host memory is pageable memory. 223If the memory is not pageable, call wait() on event return by memcpy API 224to ensure synchronization behavior. 225*/ 226if (ng )ck (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy ( 227ptr ,p .data (),p .size ()* 8 ).wait ()), 228"ptr" ); 229/* 230DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, 231assuming in the original code the source host memory is pageable memory. 232If the memory is not pageable, call wait() on event return by memcpy API 233to ensure synchronization behavior. 234*/ 235ck (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy (start ,st .data (), 236st .size ()* 4 ).wait ()), 237"start" ); 238ck (DPCT_CHECK_ERROR ( 239 (dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy (n ,& ng ,4 ).wait ()), 240"n" ); 241/* 242DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, 243assuming in the original code the source host memory is pageable memory. 244If the memory is not pageable, call wait() on event return by memcpy API 245to ensure synchronization behavior. 246*/ 247ck (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy (dst ,ds .data (), 248ds .size ()* 4 ).wait ()), 249"dst" ); 250/* 251DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, 252assuming in the original code the source host memory is pageable memory. 253If the memory is not pageable, call wait() on event return by memcpy API 254to ensure synchronization behavior. 255*/ 256ck (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy (tok ,tk_v .data (), 257tk_v .size ()* 4 ).wait ()), 258"tok" ); 259return ng ; 260 } 261void call (int64_t grid_groups , dpct::queue_ptr s ) { 262 k::native_expert_grouped (L ,ptr ,start ,n ,dst ,tok ,cap ,cap ,xq ,scr ,out ,s ,grid_groups ); 263 } 264// `out` after one call from the NaN pattern, the scratch holding `junk` (what earlier calls left there) 265 std::vector < uint32_t > result (bool v1 ,int64_t grid_groups ,int junk , 266 dpct::queue_ptr s ) { 267ck (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()) 268 .memset (out ,0xFF ,out_floats * 4 ) 269 .wait ()), 270"memset" ); 271ck (DPCT_CHECK_ERROR ( 272 (dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memset (scr ,junk ,scr_bytes ).wait ()), 273"memset" ); 274 k::native_grouped_set_v1 (v1 ); 275call (grid_groups ,s ); 276 k::native_grouped_set_v1 (false); 277ck (DPCT_CHECK_ERROR (s -> wait ()),"sync" ); 278 std::vector < uint32_t > o (out_floats ); 279ck (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()) 280 .memcpy (o .data (),out ,o .size ()* 4 ) 281 .wait ()), 282"out" ); 283return o ; 284 } 285}; 286 287void check (int gu ,int dt ,int64_t H ,int64_t FF , dpct::queue_ptr s , 288 std::mt19937 & rng ) { 289Setup S (gu ,dt ,H ,FF ,6 ,4 ,9 ,rng ,s );// 6 tokens x 4 experts: cap 24 entries 290int calls = 0 ,bad = 0 ; 291size_t written = 0 ; 292for (const int base : {0 ,7 }) { 293for (const int groups : {0 ,1 ,2 ,3 ,5 ,8 ,24 }) { 294const int ng = S .plan (groups ,base ,rng ); 295const auto ref = S .result (true,0 ,0x00 ,s ); 296size_t w = 0 ; 297for (const uint32_t v :ref )w += v != 0xFFFFFFFFu ; 298written += w ; 299for (const int64_t gy : {(int64_t )0 , (int64_t )1 , (int64_t )2 , (int64_t )3 , (int64_t )4 , (int64_t )S .cap + 3 }) { 300const auto got = S .result (false,gy , (calls & 1 ) ?0x7F :0x00 ,s ); 301++ calls ; 302size_t diff = 0 ; 303for (size_t i = 0 ;i < ref .size ();++ i )diff += ref [i ]!= got [i ]; 304if (diff ) { 305 std::printf (" %-8s/%-7s base %d, %d groups, grid_groups %lld: %zu of %zu floats differ FAIL\n" , 306name_of (gu ),name_of (dt ),base ,ng , (long long )gy ,diff ,ref .size ()); 307++ bad ; 308 } 309 } 310 } 311 } 312 std::printf ("%-8s/%-7s %5lld x %4lld %d calls: %s (%zu output floats written in all)\n" ,name_of (gu ),name_of (dt ), 313 (long long )H , (long long )FF ,calls ,bad ?"FAIL" :"bitwise equal to v1" ,written ); 314if (written == 0 ) { std::printf (" nothing was written: the check checked nothing FAIL\n" );++ bad ; } 315g_fail += bad ; 316} 317 318// ------------------------------------------------------------------------------------------------ --kq 319// MODEL-UPDATE (Intel): the K-quant / Q5_1 / Q8_0 multi-entry split (native_expert_set_kq_split) against the per-entry 320// kernels, bitwise; and both against a CPU reference in float: ggml's dequantize_row_* of the weights, the q8_1 321// activations' own values (d x q), SwiGLU in float (the GPU re-quantizes h to q8_1 for the down product, the reference 322// does not: that rounding is the tolerance, 3e-2 of the output's largest magnitude). 323float h2f (const uint8_t * p ) { 324uint16_t h ; 325 std::memcpy (& h ,p ,2 ); 326return (float ) sycl::bit_cast < sycl::half > (h ); 327} 328// ggml-quants.c dequantize_row_* (one block) 329void dq_block (int t ,const uint8_t * b ,float * y ) { 330switch (t ) { 331case 8 : {// Q8_0: d, qs[32] 332const float d = h2f (b ); 333for (int i = 0 ;i < 32 ;++ i )y [i ]= d * (float ) (int8_t )b [2 + i ]; 334break ; 335 } 336case 7 : {// Q5_1: d, m, qh[4], qs[16] 337const float d = h2f (b ),m = h2f (b + 2 ); 338uint32_t qh ; 339 std::memcpy (& qh ,b + 4 ,4 ); 340const uint8_t * qs = b + 8 ; 341for (int j = 0 ;j < 16 ;++ j ) { 342const uint8_t xh0 = ((qh >>j ) <<4 )& 0x10 ,xh1 = ((qh >> (j + 12 )))& 0x10 ; 343y [j ]= (float ) ((qs [j ]& 0x0F ) |xh0 )* d + m ; 344y [j + 16 ]= (float ) ((qs [j ] >>4 ) |xh1 )* d + m ; 345 } 346break ; 347 } 348case 12 :case 13 : {// Q4_K: d, dmin, scales[12], qs[128]; Q5_K: d, dmin, scales[12], qh[32], qs[128] 349const float d = h2f (b ),dmin = h2f (b + 2 ); 350const uint8_t * sc = b + 4 ; 351const uint8_t * qh = b + 16 ; 352const uint8_t * ql = t == 12 ?b + 16 :b + 48 ; 353auto smk = [& ](int j ,uint8_t & s ,uint8_t & m ) { 354if (j < 4 ) {s = sc [j ]& 63 ;m = sc [j + 4 ]& 63 ; } 355else {s = (sc [j + 4 ]& 0xF ) | ((sc [j - 4 ] >>6 ) <<4 );m = (sc [j + 4 ] >>4 ) | ((sc [j ] >>6 ) <<4 ); } 356 }; 357int is = 0 ; 358uint8_t u1 = 1 ,u2 = 2 ; 359for (int j = 0 ;j < 256 ;j += 64 ) { 360uint8_t s ,m ; 361smk (is ,s ,m ); 362const float d1 = d * s ,m1 = dmin * m ; 363smk (is + 1 ,s ,m ); 364const float d2 = d * s ,m2 = dmin * m ; 365for (int l = 0 ;l < 32 ;++ l ) 366* y ++ = d1 * (float ) ((ql [l ]& 0xF )+ (t == 13 && (qh [l ]& u1 ) ?16 :0 ))- m1 ; 367for (int l = 0 ;l < 32 ;++ l ) 368* y ++ = d2 * (float ) ((ql [l ] >>4 )+ (t == 13 && (qh [l ]& u2 ) ?16 :0 ))- m2 ; 369ql += 32 ;is += 2 ;u1 <<=2 ;u2 <<=2 ; 370 } 371break ; 372 } 373case 14 : {// Q6_K: ql[128], qh[64], scales[16], d 374const uint8_t * ql = b ; 375const uint8_t * qh = b + 128 ; 376const int8_t * sc = (const int8_t * ) (b + 192 ); 377const float d = h2f (b + 208 ); 378for (int n = 0 ;n < 256 ;n += 128 ) { 379for (int l = 0 ;l < 32 ;++ l ) { 380const int is = l /16 ; 381const int q1 = (int8_t ) ((ql [l ]& 0xF ) | (((qh [l ] >>0 )& 3 ) <<4 ))- 32 ; 382const int q2 = (int8_t ) ((ql [l + 32 ]& 0xF ) | (((qh [l ] >>2 )& 3 ) <<4 ))- 32 ; 383const int q3 = (int8_t ) ((ql [l ] >>4 ) | (((qh [l ] >>4 )& 3 ) <<4 ))- 32 ; 384const int q4 = (int8_t ) ((ql [l + 32 ] >>4 ) | (((qh [l ] >>6 )& 3 ) <<4 ))- 32 ; 385y [l ]= d * sc [is ]* q1 ; 386y [l + 32 ]= d * sc [is + 2 ]* q2 ; 387y [l + 64 ]= d * sc [is + 4 ]* q3 ; 388y [l + 96 ]= d * sc [is + 6 ]* q4 ; 389 } 390y += 128 ;ql += 64 ;qh += 32 ;sc += 8 ; 391 } 392break ; 393 } 394default : std::fprintf (stderr ,"dq_block: type %d\n" ,t ); std::exit (2 ); 395 } 396} 397std::vector < float > dq_rows (int t ,const uint8_t * w ,int64_t rows ,int64_t n ) { 398const int bv = block_values (t ); 399const size_t bs = k::iq_row_bytes (t ,bv ); 400 std::vector < float > y ((size_t )rows * n ); 401for (size_t b = 0 ;b < y .size () /bv ;++ b )dq_block (t ,w + b * bs ,& y [b * bv ]); 402return y ; 403} 404// the CPU reference of the last plan's call: out rows ent_dst[e] (n_embd floats each) 405std::vector < float > reference (const Setup & S ) { 406const int64_t H = S .L .n_embd ,FF = S .L .n_ff ; 407 std::vector < float > ref (S .out_floats , std::nanf ("" )); 408 std::vector < float > x (H ); 409for (size_t g = 0 ;g + 1 < S .h_start .size ();++ g ) { 410const auto & blob = S .hb [S .h_blob [g ]]; 411const auto G = dq_rows (S .L .gu_type ,blob .data (),FF ,H ); 412const auto U = dq_rows (S .L .gu_type ,blob .data ()+ S .L .up_off ,FF ,H ); 413const auto D = dq_rows (S .L .d_type ,blob .data ()+ S .L .down_off ,H ,FF ); 414for (int e = S .h_start [g ];e < S .h_start [g + 1 ];++ e ) { 415const uint8_t * xb = & S .h_xq [(size_t )S .h_tok [e ]* (H /32 )* 36 ]; 416for (int64_t i = 0 ;i < H ;++ i )x [i ]= h2f (xb + (i /32 )* 36 )* (float ) (int8_t )xb [(i /32 )* 36 + 4 + i %32 ]; 417 std::vector < float > h (FF ); 418for (int64_t r = 0 ;r < FF ;++ r ) { 419double gs = 0 ,us = 0 ; 420for (int64_t i = 0 ;i < H ;++ i ) {gs += (double )G [r * H + i ]* x [i ];us += (double )U [r * H + i ]* x [i ]; } 421h [r ]= (float ) (gs / (1.0 + std::exp (- gs ))* us ); 422 } 423for (int64_t r = 0 ;r < H ;++ r ) { 424double s = 0 ; 425for (int64_t i = 0 ;i < FF ;++ i )s += (double )D [r * FF + i ]* h [i ]; 426ref [(size_t )S .h_dst [e ]* H + r ]= (float )s ; 427 } 428 } 429 } 430return ref ; 431} 432void check_kq (int gu ,int dt ,int64_t H ,int64_t FF , dpct::queue_ptr s , std::mt19937 & rng ) { 433Setup S (gu ,dt ,H ,FF ,6 ,4 ,9 ,rng ,s );// groups of 1..6 entries: the split's chunks of 4 and 2 and the rest 434int calls = 0 ,bad = 0 ; 435double worst = 0 ; 436for (const int groups : {1 ,2 ,3 ,5 ,8 }) { 437const int ng = S .plan (groups ,0 ,rng ); 438 k::native_expert_set_kq_split (false); 439const auto a = S .result (false,0 ,0x00 ,s ); 440 k::native_expert_set_kq_split (true); 441const auto b = S .result (false,0 ,0x7F ,s ); 442++ calls ; 443size_t diff = 0 ; 444for (size_t i = 0 ;i < a .size ();++ i )diff += a [i ]!= b [i ]; 445if (diff ) { 446 std::printf (" %-6s/%-6s %d groups: split vs per-entry: %zu of %zu floats differ FAIL\n" ,name_of (gu ),name_of (dt ), 447ng ,diff ,a .size ()); 448++ bad ; 449 } 450const auto ref = reference (S ); 451double amax = 0 ,emax = 0 ; 452size_t n = 0 ; 453for (size_t i = 0 ;i < ref .size ();++ i ) { 454if (std::isnan (ref [i ]))continue ; 455float g ; 456 std::memcpy (& g ,& b [i ],4 ); 457amax = std::max (amax , (double ) std::fabs (ref [i ])); 458emax = std::max (emax , (double ) std::fabs (g - ref [i ])); 459++ n ; 460 } 461const double rel = amax > 0 ?emax /amax :1.0 ; 462worst = std::max (worst ,rel ); 463if (n == 0 || !(rel < 3e-2 )) { 464 std::printf (" %-6s/%-6s %d groups: GPU vs CPU reference: max err %.3g of %.3g (%zu values) FAIL\n" ,name_of (gu ), 465name_of (dt ),ng ,emax ,amax ,n ); 466++ bad ; 467 } 468 } 469 std::printf ("%-6s/%-6s %5lld x %4lld %d calls: split %s, CPU reference worst %.2e of the largest output\n" ,name_of (gu ), 470name_of (dt ), (long long )H , (long long )FF ,calls ,bad ?"FAIL" :"bitwise equal to per-entry" ,worst ); 471g_fail += bad ; 472} 473 474// ------------------------------------------------------------------------------------------------ --bench 475// A window's 48 calls, one per layer, each with ITS OWN experts as the layers have: copies of the Setup's blobs in one 476// arena, so the weights stream from DRAM as in the engine. (48 calls re-reading the same 28 experts - 73 MB, about an 477// Ada L2 - would read part of them from L2; the engine's layers share none.) 478struct Layers { 479uint8_t * arena = nullptr ; 480 std::vector < unsigned long long *> ptr ;// per layer: its groups' blobs (device) 481Layers (Setup & S ,int ng ) { 482const int per = std::max (ng ,1 ); 483arena = dalloc < uint8_t > (S .slot * (size_t ) (48 * per )); 484for (int l = 0 ;l < 48 ;++ l ) { 485 std::vector < unsigned long long > p ; 486for (int j = 0 ;j < per ;++ j ) { 487uint8_t * d = arena + S .slot * (size_t ) (l * per + j ); 488ck (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy ( 489d , 490S .blobs + S .slot * (size_t )((l * per + j ) %S .n_blobs ), 491S .L .bytes ).wait ()), 492"blob copy" ); 493p .push_back ((unsigned long long )d ); 494 } 495unsigned long long * dp = dalloc < unsigned long long > (p .size ()); 496/* 497DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, 498assuming in the original code the source host memory is pageable 499memory. If the memory is not pageable, call wait() on event return 500by memcpy API to ensure synchronization behavior. 501*/ 502ck (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy ( 503dp ,p .data (),p .size ()* 8 ).wait ()), 504"ptr" ); 505ptr .push_back (dp ); 506 } 507 } 508Layers (const Layers & )= delete ; 509Layers & operator= (const Layers & )= delete ; 510 ~Layers () { 511for (auto * p :ptr ) 512DPCT_CHECK_ERROR (sycl::free (p , dpct::get_in_order_queue ())); 513 sycl::free (arena , dpct::get_in_order_queue ()); 514 } 515}; 516 517// the 48 calls of one variant captured in one graph 518dpct::experimental::command_graph_exec_ptr 519make_graph (dpct::queue_ptr s ,Setup & S ,const Layers & Ls ,bool v1 ,int64_t gy ) { 520 k::native_grouped_set_v1 (v1 ); 521 dpct::experimental::command_graph_ptr g ; 522 dpct::experimental::command_graph_exec_ptr ge ; 523ck (DPCT_CHECK_ERROR (dpct::experimental::begin_recording (s )),"capture" ); 524for (int l = 0 ;l < 48 ;++ l ) 525 k::native_expert_grouped (S .L ,Ls .ptr [l ],S .start ,S .n ,S .dst ,S .tok ,S .cap ,S .cap ,S .xq ,S .scr ,S .out ,s ,gy ); 526ck (DPCT_CHECK_ERROR (dpct::experimental::end_recording (s ,& g )),"capture" ); 527ck (DPCT_CHECK_ERROR ( 528ge = new sycl::ext::oneapi::experimental::command_graph < 529 sycl::ext::oneapi::experimental::graph_state::executable > ( 530g -> finalize ())), 531"instantiate" ); 532ck (DPCT_CHECK_ERROR (delete (g )),"graph" ); 533 k::native_grouped_set_v1 (false); 534return ge ; 535} 536 537// one launch of the graph: microseconds per call 538float launch_us (dpct::queue_ptr s , 539 dpct::experimental::command_graph_exec_ptr ge , 540 dpct::event_ptr e0 , dpct::event_ptr e1 ) { 541/* 542DPCT1024: The original code returned the error code that was further 543consumed by the program logic. This original code was replaced with 0. You 544may need to rewrite the program logic consuming the error code. 545*/ 546ck (DPCT_CHECK_ERROR (dpct::sync_barrier (e0 ,s )),"record" ); 547ck (DPCT_CHECK_ERROR (s -> ext_oneapi_graph (* ge )),"launch" ); 548/* 549DPCT1024: The original code returned the error code that was further 550consumed by the program logic. This original code was replaced with 0. You 551may need to rewrite the program logic consuming the error code. 552*/ 553ck (DPCT_CHECK_ERROR (dpct::sync_barrier (e1 ,s )),"record" ); 554ck (DPCT_CHECK_ERROR (e1 -> wait_and_throw ()),"bench" ); 555float ms = 0 ; 556ck (DPCT_CHECK_ERROR ( 557ms = (e1 -> get_profiling_info < 558 sycl::info::event_profiling::command_end > ()- 559e0 -> get_profiling_info < 560 sycl::info::event_profiling::command_start > ()) / 5611000000.0f ), 562"elapsed" ); 563return 1e3f * ms /48.0f ; 564} 565 566float median (std::vector < float > v ) { 567 std::sort (v .begin (),v .end ()); 568return v [v .size () /2 ]; 569} 570 571// The two variants' launches ALTERNATE (v1-new, new-v1, ...) after a warm-up, and each reports its median: a card 572// under sustained load steps its clock down after a fraction of a second (an RTX 4080 SUPER went from 80 to 89 us 573// per gate/up call within one run), and whichever variant ran before the step would look faster. 574constexpr int kWarmPairs = 20 ,kPairs = 40 ; 575 576void bench (dpct::queue_ptr s , std::mt19937 & rng ) { 577 std::printf ("\n--bench: microseconds per call, a window's 48 calls in a graph, each layer with its own experts (the\n" 578"weights stream from DRAM as in the engine); v1 / new (grid_groups): medians of %d launches each,\n" 579"alternating, after %d warm-up pairs - idle GPU assumed\n" ,kPairs ,kWarmPairs ); 580// a verify window's shape: 4 tokens x 10 experts, 2560 x 768 IQ3_S / IQ4_XS experts 581Setup S (21 ,23 ,2560 ,768 ,4 ,10 ,32 ,rng ,s ); 582 std::vector < int > vram (16 ,1 ); 583vram .insert (vram .end (),12 ,2 );// 28 groups, 40 entries 584const struct {const char * what ; std::vector < int > sizes ;int64_t gy ; }rows []= { 585 {"no group (the PCIe call at pcie_frac 0)" , {},4 }, 586 {"1 group of 2 entries (a PCIe call)" , {2 },4 }, 587 {"28 groups, 40 entries (a VRAM call)" ,vram ,0 }, 588 }; 589 dpct::event_ptr e0 ,e1 ; 590ck (DPCT_CHECK_ERROR (e0 = new sycl::event ()),"event" ); 591ck (DPCT_CHECK_ERROR (e1 = new sycl::event ()),"event" ); 592for (const auto & r :rows ) { 593const int ng = S .plan_sizes (r .sizes ,0 ,rng ); 594const Layers Ls (S ,ng );// 48 x 28 experts: 3.7 GB for the VRAM call 595 dpct::experimental::command_graph_exec_ptr ga = make_graph (s ,S ,Ls , 596 true,0 ), 597gb = make_graph (s ,S ,Ls , 598 false,r .gy ); 599 std::vector < float > ta ,tb ; 600for (int i = 0 ;i < kWarmPairs + kPairs ;++ i ) { 601const bool a_first = i %2 == 0 ; 602const float x = launch_us (s ,a_first ?ga :gb ,e0 ,e1 ),y = launch_us (s ,a_first ?gb :ga ,e0 ,e1 ); 603if (i < kWarmPairs )continue ; 604ta .push_back (a_first ?x :y ); 605tb .push_back (a_first ?y :x ); 606 } 607ck (DPCT_CHECK_ERROR (delete (ga )),"graph" ); 608ck (DPCT_CHECK_ERROR (delete (gb )),"graph" ); 609 std::printf (" %-42s %8.2f / %8.2f us (grid_groups %lld)\n" ,r .what ,median (ta ),median (tb ), (long long )r .gy ); 610 } 611 dpct::destroy_event (e0 ); 612 dpct::destroy_event (e1 ); 613} 614 615// ------------------------------------------------------------------------------------------------ --kqbench [NL [host]] 616// Unsloth's formats against the IQ packs' at the model's shapes (2560 x 640): microseconds per grouped call and the 617// expert bytes it reads per microsecond. NL layers (default 16), each with its own experts, so the weights stream from 618// DRAM; a call reads each of its groups' whole blobs (gate + up + down) once. Shapes: one token (10 groups of 1), a 619// window of 2 tokens (16 groups, 20 entries) and of 4 (28 groups, 40 entries; native_grouped_parity's --bench). 620// STRATA_GU_LANES / STRATA_DOWN_LANES pick the lane split as in the engine. 621void kq_bench (dpct::queue_ptr s , std::mt19937 & rng ,int nl ,bool host ) { 622const int pairs [][2 ]= {{21 ,20 }, {23 ,20 }, {18 ,42 }, {12 ,7 }, {12 ,8 }, {13 ,8 }, 623#ifdef STRATA_Q6K_EXPERTS 624 {14 ,8 }, 625#endif 626 {8 ,8 }}; 627 std::vector < int > w1 (10 ,1 ),w2 (12 ,1 ),w4 (16 ,1 ); 628w2 .insert (w2 .end (),4 ,2 );// 16 groups, 20 entries 629w4 .insert (w4 .end (),12 ,2 );// 28 groups, 40 entries 630const struct {const char * what ;int T ;const std::vector < int >* sizes ; }shapes []= { 631 {"1 token, 10x1" ,1 ,& w1 }, {"2 tokens, 16 groups / 20" ,2 ,& w2 }, {"4 tokens, 28 groups / 40" ,4 ,& w4 }}; 632 dpct::event_ptr e0 = new sycl::event (),e1 = new sycl::event (); 633 std::printf ("\n--kqbench: %d layers per graph, each its own experts (%s); us per call (median of 40), expert MB per call, GB/s\n" , 634nl ,host ?"pinned host memory" :"device memory" ); 635for (const auto & pr :pairs ) { 636for (const auto & sh :shapes ) { 637Setup S (pr [0 ],pr [1 ],2560 ,640 ,sh .T ,10 ,28 ,rng ,s ); 638const int ng = S .plan_sizes (* sh .sizes ,0 ,rng ); 639// host: the arena in pinned host memory, read by the kernels over PCIe (the B70's mirrored experts) 640uint8_t * arena = host ? (uint8_t * ) sycl::malloc_host (S .slot * (size_t ) (nl * ng )+ 256 , dpct::get_in_order_queue ()) 641 :dalloc < uint8_t > (S .slot * (size_t ) (nl * ng )); 642 std::vector < unsigned long long *> lp ; 643for (int l = 0 ;l < nl ;++ l ) { 644 std::vector < unsigned long long > p ; 645for (int j = 0 ;j < ng ;++ j ) { 646uint8_t * d = arena + S .slot * (size_t ) (l * ng + j ); 647 dpct::get_in_order_queue ().memcpy (d ,S .blobs + S .slot * (size_t ) (j %S .n_blobs ),S .L .bytes ).wait (); 648p .push_back ((unsigned long long )d ); 649 } 650unsigned long long * dp = dalloc < unsigned long long > (p .size ()); 651 dpct::get_in_order_queue ().memcpy (dp ,p .data (),p .size ()* 8 ).wait (); 652lp .push_back (dp ); 653 } 654 dpct::experimental::command_graph_ptr g ; 655 dpct::experimental::begin_recording (s ); 656for (int l = 0 ;l < nl ;++ l ) 657 k::native_expert_grouped (S .L ,lp [l ],S .start ,S .n ,S .dst ,S .tok ,S .cap ,S .cap ,S .xq ,S .scr ,S .out ,s ,0 ); 658 dpct::experimental::end_recording (s ,& g ); 659auto * ge = new sycl::ext::oneapi::experimental::command_graph < 660 sycl::ext::oneapi::experimental::graph_state::executable > (g -> finalize ()); 661delete g ; 662 std::vector < float > t ; 663for (int i = 0 ;i < 60 ;++ i ) { 664const float us = launch_us (s ,ge ,e0 ,e1 )* 48.0f / (float )nl ; 665if (i >=20 )t .push_back (us ); 666 } 667delete ge ; 668const double mb = (double )ng * (double )S .L .bytes /1e6 ,us = median (t ); 669 std::printf (" %-7s/%-6s %-26s %8.2f us %6.2f MB %6.1f GB/s\n" ,name_of (pr [0 ]),name_of (pr [1 ]),sh .what ,us , 670mb ,mb * 1e3 /us ); 671for (auto * p :lp ) sycl::free (p , dpct::get_in_order_queue ()); 672 sycl::free (arena , dpct::get_in_order_queue ()); 673 } 674 } 675 dpct::destroy_event (e0 ); 676 dpct::destroy_event (e1 ); 677} 678 679}// namespace 680 681int main (int argc ,char ** argv ) { 682const bool do_bench = argc > 1 && std::string (argv [1 ])== "--bench" ; 683 dpct::queue_ptr s ; 684ck (DPCT_CHECK_ERROR (s = dpct::get_current_device ().create_queue (true)), 685"stream" ); 686 std::mt19937 rng (316 ); 687if (argc > 1 && std::string (argv [1 ])== "--kqbench" ) {// timings only (the checks: run without arguments) 688kq_bench (s ,rng ,argc > 2 ? std::atoi (argv [2 ]) :16 ,argc > 3 && std::string (argv [3 ])== "host" ); 689 dpct::get_current_device ().destroy_queue (s ); 690return 0 ; 691 } 692// Q4-KQ: the K-quant downs of a UD file at expert widths divisible by 256 (Qwen3.6's UD-Q4_K_XL: Q4_K / Q5_K gate/up, Q5_K / Q6_K 693// down, 2048 x 512), split vs per-entry bitwise and the GPU against the CPU reference, at the widths 512 and 1024 694auto kq_down = [& ] { 695// Q4-SYCL: and the hidden width the build is compiled for (3072 in q4_mid, 4096 in q4_big; the pools' buffers follow it) 696 std::vector < int64_t > Hs = {2048 ,2560 }; 697if (std::find (Hs .begin (),Hs .end (), (int64_t ) strata::core::kCompiledGeometry .n_embd )== Hs .end ())Hs .push_back (strata::core::kCompiledGeometry .n_embd ); 698const int gus []= {12 ,13 }; 699for (const int gu :gus ) 700for (const int dt : {13 701#ifdef STRATA_Q6K_EXPERTS 702 ,14 703#endif 704 }) 705for (const int64_t H :Hs ) 706for (const int64_t FF : {512 ,1024 })check_kq (gu ,dt ,H ,FF ,s ,rng ); 707 }; 708// Q4-KQ: --hash, a checksum of the grouped expert call's output bytes for every pair of today's sets (the IQ3_XXS pack and the 709// Unsloth UD sets at the model's 2560 x 640), fixed seeds: run on the build before and after a kernel change, the lines must be 710// identical (the A750 is not repeatable end to end, but a kernel call on fixed inputs is) 711if (argc > 1 && std::string (argv [1 ])== "--hash" ) { 712const int pairs [][2 ]= {{18 ,42 }, {18 ,20 }, {18 ,6 }, {18 ,8 }, {21 ,20 }, {21 ,6 }, {21 ,8 }, {21 ,42 }, {23 ,20 }, {23 ,6 }, {16 ,42 }, {17 ,20 }, 713 {22 ,42 }, {29 ,42 }, {42 ,42 }, {42 ,20 }, {12 ,7 }, {12 ,8 }, {13 ,8 }, {13 ,7 }, {14 ,8 }, {8 ,8 }}; 714for (const auto & pr :pairs ) { 715for (const int64_t FF : {640 }) { 716 std::mt19937 r2 (4242 + pr [0 ]* 64 + pr [1 ]); 717Setup S (pr [0 ],pr [1 ],2560 ,FF ,6 ,4 ,9 ,r2 ,s ); 718uint64_t h = 1469598103934665603ull ; 719for (const int groups : {1 ,3 ,5 ,8 }) { 720S .plan (groups ,0 ,r2 ); 721const auto b = S .result (false,0 ,0x7F ,s ); 722for (const auto v :b ) {h ^= (uint64_t )v ;h *=1099511628211ull ; } 723 } 724 std::printf ("HASH %s/%s 2560 x %lld %016llx\n" ,name_of (pr [0 ]),name_of (pr [1 ]), (long long )FF , (unsigned long long )h ); 725 } 726 } 727 dpct::get_current_device ().destroy_queue (s ); 728return 0 ; 729 } 730if (argc > 1 && std::string (argv [1 ])== "--kqdown" ) { 731kq_down (); 732 std::printf ("native_grouped_parity --kqdown: %d failures\n" ,g_fail ); 733 dpct::get_current_device ().destroy_queue (s ); 734return g_fail ?1 :0 ; 735 } 736if (argc > 1 && std::string (argv [1 ])== "--kq" ) {// the K-quant split and the CPU reference only 737const int pairs [][2 ]= {{12 ,7 }, {12 ,8 }, {13 ,8 }, {14 ,8 }, {8 ,8 }, {13 ,7 }}; 738for (const auto & pr :pairs )check_kq (pr [0 ],pr [1 ],2560 ,640 ,s ,rng );// the model's shapes 739for (const auto & pr :pairs )check_kq (pr [0 ],pr [1 ],512 ,256 ,s ,rng ); 740 std::printf ("native_grouped_parity --kq: %d failures\n" ,g_fail ); 741 dpct::get_current_device ().destroy_queue (s ); 742return g_fail ?1 :0 ; 743 } 744for (int gu : {16 ,17 ,18 ,21 ,22 ,23 ,29 ,42 ,12 ,13 , 745#ifdef STRATA_Q6K_EXPERTS 74614 , 747#endif 7488 })// STRATA_GU_FMTS 749for (int dt : {20 ,23 ,42 ,7 ,8 ,6 ,13 })check (gu ,dt ,512 ,256 ,s ,rng );// STRATA_D_FMTS (6 = Q5_0: UD-IQ4_XS / Q3_K_XL); IQ4_XS: n_ff % 256 750kq_down ();// Q4-KQ: Q5_K / Q6_K downs at widths 512 and 1024 751check (21 ,20 ,2560 ,640 ,s ,rng );// a model's shapes 752// round 0214: every expert type pair of the new Unsloth Qwen3.8-Flash-Next sets at the model's 2560 x 640 753// (IQ1_M/IQ2_XXS/IQ2_XS/IQ2_S/Q2_0/IQ3_XXS/IQ4_XS gate/up; Q2_0/IQ4_NL/Q5_0/Q8_0 down; IQ4_XS is 256-wide so n_ff 640 needs a 32-block down) 754for (int gu : {29 ,16 ,17 ,22 ,42 ,18 ,23 }) 755for (int dt : {42 ,20 ,6 ,8 })check (gu ,dt ,2560 ,640 ,s ,rng ); 756check (21 ,23 ,2560 ,768 ,s ,rng ); 757// Q4-SYCL: the build's own expert shape (q4_lite 2048 x 512, q4_mid 3072 x 1024, q4_big 4096 x 1024): the UD mix's pairs (Q4_K / Q5_K gate/up; 758// Q5_K, Q6_K, Q5_1, IQ4_NL, Q8_0 downs) against the CPU reference and split vs per-entry 759if (strata::core::kCompiledGeometry .n_embd != 2560 || strata::core::kCompiledGeometry .n_ff != 640 ) { 760const int64_t KH = strata::core::kCompiledGeometry .n_embd ,KF = strata::core::kCompiledGeometry .n_ff ; 761 std::printf ("compiled shape %lld x %lld\n" , (long long )KH , (long long )KF ); 762for (int gu : {12 ,13 }) 763for (int dt : {13 , 764#ifdef STRATA_Q6K_EXPERTS 76514 , 766#endif 7677 ,8 })// (check_kq's reference has no IQ4_NL down: those pairs are in the loop below) 768check_kq (gu ,dt ,KH ,KF ,s ,rng ); 769for (int gu : {29 ,16 ,17 ,22 ,42 ,18 ,23 ,21 }) 770for (int dt : {42 ,20 ,6 ,8 })check (gu ,dt ,KH ,KF ,s ,rng ); 771 } 772if (do_bench )bench (s ,rng ); 773 std::printf ("native_grouped_parity: %d failures\n" ,g_fail ); 774 dpct::get_current_device ().destroy_queue (s ); 775return g_fail ?1 :0 ; 776}