okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
5438023a6
main
1// src/kernels/cuda/qsa_select.cu - see include/strata/kernels/qsa_select.hpp. 2#define DPCT_PROFILING_ENABLED 3#include <sycl/sycl.hpp> 4#include "strata/kprof.hpp" 5#include "strata/core/geometry.hpp" 6#include <dpct/dpct.hpp> 7#include "strata/sycl_queue.hpp" 8#include "strata/core/emulate.hpp" 9#include <cstdlib> 10#include <cstring> 11#include "strata/kernels/qsa_select.hpp" 12#include "strata/kernels/gfx_arch.hpp" 13 14#include <cfloat> 15#include <cstdio> 16#include <cstdlib> 17#include <cstring> 18 19namespace strata::kernels { 20namespace { 21 22constexpr int IDX_DIM = 128 ,IDX_HEADS = 4 ,R = 4 ; 23static_assert(IDX_DIM == strata::core::kCompiledGeometry .idx_key_dim && IDX_HEADS == strata::core::kCompiledGeometry .idx_q_heads && R == strata::core::kCompiledGeometry .idx_block , 24"qsa_select is compiled for core/geometry.hpp" ); 25constexpr int SCORE_WARPS = 8 ; 26constexpr int TOPK_T = 256 ; 27 28__dpct_inline__ uint32_t order_key (float s ) { 29const float v = s + 0.0f ; 30if (!(v == v ))return 0u ; 31const uint32_t b = sycl::bit_cast < unsigned int > (v ); 32return (b & 0x80000000u ) ? ~b : (b |0x80000000u ); 33} 34 35__dpct_inline__ void block_scores_kernel (const float * __restrict__pooled , 36const float * __restrict__dead , 37const float * __restrict__q_idx , 38const int32_t * __restrict__steps , 39int64_t max_blocks , 40float * __restrict__out ) { 41auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item < 3 > (); 42const int64_t qi = item_ct1 .get_group (1 ); 43const int32_t * st = steps + qi * kStepCount ; 44const int64_t n_kv = st [kStepNKv ],n_bid = st [kStepNBid ]; 45const int64_t b = (int64_t )item_ct1 .get_group (2 )* SCORE_WARPS + 46 (item_ct1 .get_local_id (2 ) >>5 ); 47if (b > n_bid || b >=max_blocks )return ; 48const int lane = item_ct1 .get_local_id (2 )& 31 ; 49const float * key = (b == n_bid ) ?dead :pooled + b * IDX_DIM ; 50const sycl::float4 k4 = 51* reinterpret_cast < const sycl::float4 *> (key + lane * 4 ); 52const float * q = q_idx + qi * IDX_HEADS * IDX_DIM + lane * 4 ; 53float score = 0.0f ; 54#pragma unroll 55for (int h = 0 ;h < IDX_HEADS ;++ h ) { 56const sycl::float4 q4 = 57* reinterpret_cast < const sycl::float4 *> (q + h * IDX_DIM ); 58float d = k4 .x ()* q4 .x ()+ k4 .y ()* q4 .y ()+ k4 .z ()* q4 .z ()+ 59k4 .w ()* q4 .w (); 60#pragma unroll 61/* 62DPCT1108: '__shfl_xor_sync' was migrated with the experimental 63feature masked sub_group function which may not be supported by all 64compilers or runtimes. You may need to adjust the code. 65*/ 66for (int o = 16 ;o > 0 ;o >>=1 )d += 67 dpct::experimental::permute_sub_group_by_xor ( 680xffffffffu , sycl::ext::oneapi::this_work_item::get_sub_group (), 69d ,o ); 70score += d > 0.0f ?d :0.0f ; 71 } 72if (lane == 0 ) { 73if (b == n_bid && n_kv %R != 0 )score += 1e9f ; 74out [qi * max_blocks + b ]= score ; 75 } 76} 77 78/* 79DPCT1110: The total declared local variable size in device function 80block_topk_kernel exceeds 128 bytes and may cause high register pressure. 81Consult with your hardware vendor to find the total register size available and 82adjust the code, or use smaller sub-group size to avoid high register pressure. 83*/ 84__dpct_inline__ void block_topk_kernel (const float * __restrict__scores , 85const int32_t * __restrict__steps , 86int64_t max_blocks ,int64_t cap , 87int32_t * __restrict__ids ) { 88auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item < 3 > (); 89auto & hist = * sycl::ext::oneapi::group_local_memory_for_overwrite < int [256 ]> ( 90 sycl::ext::oneapi::this_work_item::get_work_group < 3 > ()); 91auto & s_a = 92* sycl::ext::oneapi::group_local_memory_for_overwrite < int [TOPK_T ]> ( 93 sycl::ext::oneapi::this_work_item::get_work_group < 3 > ()); 94auto & s_b = 95* sycl::ext::oneapi::group_local_memory_for_overwrite < int [TOPK_T ]> ( 96 sycl::ext::oneapi::this_work_item::get_work_group < 3 > ()); 97auto & s_digit = * sycl::ext::oneapi::group_local_memory_for_overwrite < int > ( 98 sycl::ext::oneapi::this_work_item::get_work_group < 3 > ()); 99auto & s_above = * sycl::ext::oneapi::group_local_memory_for_overwrite < int > ( 100 sycl::ext::oneapi::this_work_item::get_work_group < 3 > ()); 101const int64_t qi = item_ct1 .get_group (2 ); 102const int32_t * st = steps + qi * kStepCount ; 103const int64_t n_kv = st [kStepNKv ],n_bid = st [kStepNBid ],width = st [kStepWidth ]; 104int32_t * out = ids + qi * cap ; 105const int t = item_ct1 .get_local_id (2 ); 106if (n_kv <=width ) {// everything is selected: the identity, ascending 107#pragma unroll 108for (int64_t j = t ;j < n_kv ;j += TOPK_T )out [j ]= (int32_t )j ; 109return ; 110 } 111const float * sc = scores + qi * max_blocks ; 112const int64_t nb = n_bid + 1 ;// blocks 0..n_bid, the last possibly empty 113const int64_t per = (nb + TOPK_T - 1 ) /TOPK_T ; 114const int64_t b0 = (int64_t )t * per ,b1 = (b0 + per < nb ) ?b0 + per :nb ; 115auto weight = [& ](int64_t b )-> int {return b < n_bid ?R : (int ) (n_kv - n_bid * R ); }; 116// ---- radix select: the largest key thr with (cells with key >= thr) >= width, 8 bits at a time 117uint32_t prefix = 0 ; 118int above = 0 ;// cells strictly above the digits fixed so far 119for (int shift = 24 ;shift >=0 ;shift -= 8 ) { 120#pragma unroll 121for (int i = t ;i < 256 ;i += TOPK_T )hist [i ]= 0 ; 122/* 123DPCT1118: SYCL group functions and algorithms must be encountered in 124converged control flow. You may need to adjust the code. 125*/ 126/* 127DPCT1065: Consider replacing sycl::nd_item::barrier() with 128sycl::nd_item::barrier(sycl::access::fence_space::local_space) for 129better performance if there is no access to global memory. 130*/ 131item_ct1 .barrier (); 132const uint32_t hi_mask = shift == 24 ?0u : (0xffffffffu << (shift + 8 )); 133for (int64_t b = b0 ;b < b1 ;++ b ) { 134const int w = weight (b ); 135if (w == 0 )continue ; 136const uint32_t k = order_key (sc [b ]); 137if ((k & hi_mask )== (prefix & hi_mask )) dpct::atomic_fetch_add < 138 sycl::access::address_space::generic_space > ( 139& hist [(k >>shift )& 255 ],w ); 140 } 141/* 142DPCT1118: SYCL group functions and algorithms must be encountered in 143converged control flow. You may need to adjust the code. 144*/ 145/* 146DPCT1065: Consider replacing sycl::nd_item::barrier() with 147sycl::nd_item::barrier(sycl::access::fence_space::local_space) for 148better performance if there is no access to global memory. 149*/ 150item_ct1 .barrier (); 151if (t == 0 ) { 152int cum = above ,d = 255 ; 153#pragma unroll 154for (;d > 0 ;-- d ) { 155if (cum + hist [d ] >=width )break ; 156cum += hist [d ]; 157 } 158s_digit = d ; 159s_above = cum ; 160 } 161/* 162DPCT1118: SYCL group functions and algorithms must be encountered in 163converged control flow. You may need to adjust the code. 164*/ 165/* 166DPCT1065: Consider replacing sycl::nd_item::barrier() with 167sycl::nd_item::barrier(sycl::access::fence_space::local_space) for 168better performance if there is no access to global memory. 169*/ 170item_ct1 .barrier (); 171prefix |= (uint32_t )s_digit <<shift ; 172above = s_above ; 173/* 174DPCT1118: SYCL group functions and algorithms must be encountered in 175converged control flow. You may need to adjust the code. 176*/ 177/* 178DPCT1065: Consider replacing sycl::nd_item::barrier() with 179sycl::nd_item::barrier(sycl::access::fence_space::local_space) for 180better performance if there is no access to global memory. 181*/ 182item_ct1 .barrier (); 183 } 184const uint32_t thr = prefix ; 185const int64_t eq_budget = width - above ;// cells equal to thr that fit, lowest index first 186// ---- per-thread counts of cells above and at the threshold, then their exclusive prefixes 187int gt = 0 ,eq = 0 ; 188for (int64_t b = b0 ;b < b1 ;++ b ) { 189const int w = weight (b ); 190if (w == 0 )continue ; 191const uint32_t k = order_key (sc [b ]); 192if (k > thr )gt += w ; 193else if (k == thr )eq += w ; 194 } 195s_a [t ]= gt ; 196s_b [t ]= eq ; 197/* 198DPCT1065: Consider replacing sycl::nd_item::barrier() with 199sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better 200performance if there is no access to global memory. 201*/ 202item_ct1 .barrier (); 203if (t == 0 ) { 204int ag = 0 ,ae = 0 ; 205for (int i = 0 ;i < TOPK_T ;++ i ) { 206const int g = s_a [i ],e = s_b [i ]; 207s_a [i ]= ag ;s_b [i ]= ae ; 208ag += g ;ae += e ; 209 } 210 } 211/* 212DPCT1065: Consider replacing sycl::nd_item::barrier() with 213sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better 214performance if there is no access to global memory. 215*/ 216item_ct1 .barrier (); 217const int64_t eq_before = s_b [t ]; 218int64_t my_eq = eq_budget - eq_before ; 219if (my_eq < 0 )my_eq = 0 ; 220if (my_eq > eq )my_eq = eq ; 221const int sel = gt + (int )my_eq ; 222/* 223DPCT1065: Consider replacing sycl::nd_item::barrier() with 224sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better 225performance if there is no access to global memory. 226*/ 227item_ct1 .barrier (); 228s_a [t ]= sel ; 229/* 230DPCT1065: Consider replacing sycl::nd_item::barrier() with 231sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better 232performance if there is no access to global memory. 233*/ 234item_ct1 .barrier (); 235if (t == 0 ) { 236int a = 0 ; 237for (int i = 0 ;i < TOPK_T ;++ i ) {const int c = s_a [i ];s_a [i ]= a ;a += c ; } 238 } 239/* 240DPCT1065: Consider replacing sycl::nd_item::barrier() with 241sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better 242performance if there is no access to global memory. 243*/ 244item_ct1 .barrier (); 245int64_t wpos = s_a [t ]; 246int64_t eq_left = my_eq ; 247for (int64_t b = b0 ;b < b1 ;++ b ) { 248const int w = weight (b ); 249if (w == 0 )continue ; 250const uint32_t k = order_key (sc [b ]); 251if (k > thr ) { 252#pragma unroll 253for (int c = 0 ;c < w ;++ c )out [wpos ++ ]= (int32_t )(b * R + c ); 254 }else if (k == thr ) { 255#pragma unroll 256for (int c = 0 ;c < w && eq_left > 0 ;++ c ,-- eq_left ) 257out [wpos ++ ]= (int32_t )(b * R + c ); 258 } 259 } 260} 261 262 263// ---- QSA select on tensor cores (perf-review, after D-1): the block scores of many queries are one GEMM, 264// rows (query, indexer head) x columns (blocks), K = 128, with relu per head summed. 3xTF32 (each operand split 265// into a TF32 hi and lo part, hi*hi + hi*lo + lo*hi) keeps FP32-level accuracy; the summation order differs from 266// the warp kernel, so a score can move in its last bits and a near-tie can select differently (not bitwise). 267// Blocks < n_bid only; the tail block n_bid (the `dead` key, +1e9) is scored by the warp kernel's own code. 268constexpr int TC_QT = 16 ;// queries per CTA (one m16 tile per indexer head) 269constexpr int TC_NB = 32 ;// blocks per tile (4 warps x n8) 270constexpr int TC_ITER = 4 ;// tiles per CTA (the query tile is loaded once) 271constexpr int TC_QS = IDX_HEADS * IDX_DIM + 4 ;// query row stride in floats 272constexpr int TC_KS = IDX_DIM + 4 ;// key row stride 273 274// TF32 conversion and MMA need sm_80: below it they compile to a trap and qsa_block_scores_tc refuses the device 275#if defined(__HIPCC__ )// AMD: no mma.sync / cp.async; the host keeps the warp kernel (below) 276#define STRATA_SEL_SM80 0 277#elif 0 // SYCL: inline PTX (mma/ldmatrix/cp.async) - the XMX port is pending; see tools/fixups.py 278#define STRATA_SEL_SM80 1 279#else 280#define STRATA_SEL_SM80 0 281#endif 282__dpct_inline__ uint32_t tf32_hi (float x ) { 283#if STRATA_SEL_SM80 284uint32_t r ; 285/* 286DPCT1053: Migration of device assembly code is not supported. 287*/ 288 asm("cvt.rna.tf32.f32 %0, %1;" :"=r" (r ) :"f" (x )); 289return r ; 290#else 291return sycl::bit_cast < uint32_t > (x ); 292#endif 293} 294__dpct_inline__ void mma_tf32 (float * c ,const uint32_t * a ,const uint32_t * b ) { 295#if !STRATA_SEL_SM80 296/* unreachable on SYCL: the launcher refuses this device */ 297#else 298/* 299DPCT1053: Migration of device assembly code is not supported. 300*/ 301 asmvolatile ("mma.sync.aligned.m16n8k8.row.col.f32.tf32.tf32.f32 " 302"{%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, " 303"{%0,%1,%2,%3};\n" 304 :"+f" (c [0 ]),"+f" (c [1 ]),"+f" (c [2 ]),"+f" (c [3 ]) 305 :"r" (a [0 ]),"r" (a [1 ]),"r" (a [2 ]),"r" (a [3 ]),"r" (b [0 ]), 306"r" (b [1 ])); 307#endif 308} 309 310/* 311DPCT1110: The total declared local variable size in device function 312block_scores_tc_kernel exceeds 128 bytes and may cause high register pressure. 313Consult with your hardware vendor to find the total register size available and 314adjust the code, or use smaller sub-group size to avoid high register pressure. 315*/ 316__dpct_inline__ void block_scores_tc_kernel ( 317const float * __restrict__pooled ,const float * __restrict__q_idx , 318const int32_t * __restrict__steps ,int64_t nq ,int64_t max_blocks , 319int64_t reach ,float * __restrict__out ,uint8_t * dpct_local ) { 320auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item < 3 > (); 321auto sm = (float * )dpct_local ; 322float * sQ = sm ;// [TC_QT][TC_QS] 323float * sK = sm + TC_QT * TC_QS ;// [TC_NB][TC_KS] 324auto & s_nbid = 325* sycl::ext::oneapi::group_local_memory_for_overwrite < int [TC_QT ]> ( 326 sycl::ext::oneapi::this_work_item::get_work_group < 3 > ()); 327const int t = item_ct1 .get_local_id (2 ),lane = t & 31 ,warp = t >>5 , 328gid = lane >>2 ,tig = lane & 3 ; 329const int64_t q0 = (int64_t )item_ct1 .get_group (1 )* TC_QT ; 330for (int i = t ;i < TC_QT * IDX_HEADS * IDX_DIM /4 ;i += 128 ) { 331const int r = i / (IDX_HEADS * IDX_DIM /4 ),c = i % (IDX_HEADS * IDX_DIM /4 ); 332 sycl::float4 v = sycl::float4 (0.f ,0.f ,0.f ,0.f ); 333if (q0 + r < nq )v = reinterpret_cast < const sycl::float4 *> ( 334q_idx + (q0 + r )* IDX_HEADS * IDX_DIM )[c ]; 335* reinterpret_cast < sycl::float4 *> (sQ + r * TC_QS + c * 4 )= v ; 336 } 337if (t < TC_QT )s_nbid [t ]= q0 + t < nq ?steps [(q0 + t )* kStepCount + kStepNBid ] :0 ; 338int lo_nbid = 0x7fffffff ,hi_nbid = 0 ; 339item_ct1 .barrier (sycl::access::fence_space::local_space ); 340#pragma unroll 341for (int i = 0 ;i < TC_QT ;++ i ) { 342if (q0 + i >=nq )break ; 343lo_nbid = sycl::min (lo_nbid ,s_nbid [i ]); 344hi_nbid = sycl::max (hi_nbid ,s_nbid [i ]); 345 } 346for (int it = 0 ;it < TC_ITER ;++ it ) { 347const int64_t b0 = 348 ((int64_t )item_ct1 .get_group (2 )* TC_ITER + it )* TC_NB ; 349if (b0 >=reach || b0 >=hi_nbid )break ;// blocks >= every query's n_bid: nothing to score 350/* 351DPCT1118: SYCL group functions and algorithms must be encountered in 352converged control flow. You may need to adjust the code. 353*/ 354/* 355DPCT1065: Consider replacing sycl::nd_item::barrier() with 356sycl::nd_item::barrier(sycl::access::fence_space::local_space) for 357better performance if there is no access to global memory. 358*/ 359item_ct1 .barrier ();// the previous tile's reads are done 360for (int i = t ;i < TC_NB * IDX_DIM /4 ;i += 128 ) { 361const int r = i / (IDX_DIM /4 ),c = i % (IDX_DIM /4 ); 362 sycl::float4 v = sycl::float4 (0.f ,0.f ,0.f ,0.f ); 363if (b0 + r < hi_nbid )v = reinterpret_cast < const sycl::float4 *> ( 364pooled + (b0 + r )* IDX_DIM )[c ]; 365* reinterpret_cast < sycl::float4 *> (sK + r * TC_KS + c * 4 )= v ; 366 } 367/* 368DPCT1118: SYCL group functions and algorithms must be encountered in 369converged control flow. You may need to adjust the code. 370*/ 371/* 372DPCT1065: Consider replacing sycl::nd_item::barrier() with 373sycl::nd_item::barrier(sycl::access::fence_space::local_space) for 374better performance if there is no access to global memory. 375*/ 376item_ct1 .barrier (); 377float acc [IDX_HEADS ][4 ]; 378#pragma unroll 379for (int h = 0 ;h < IDX_HEADS ;++ h )acc [h ][0 ]= acc [h ][1 ]= acc [h ][2 ]= acc [h ][3 ]= 0.f ; 380const float * kr = sK + (warp * 8 + gid )* TC_KS ; 381#pragma unroll 4 382for (int k0 = 0 ;k0 < IDX_DIM ;k0 += 8 ) { 383const float kx0 = kr [k0 + tig ],kx1 = kr [k0 + tig + 4 ]; 384uint32_t bh [2 ],bl [2 ]; 385bh [0 ]= tf32_hi (kx0 ); 386bh [1 ]= tf32_hi (kx1 ); 387bl [0 ]= tf32_hi (kx0 - sycl::bit_cast < float > (bh [0 ])); 388bl [1 ]= tf32_hi (kx1 - sycl::bit_cast < float > (bh [1 ])); 389#pragma unroll 390for (int h = 0 ;h < IDX_HEADS ;++ h ) { 391const float * qa = sQ + h * IDX_DIM + k0 + tig ; 392const float x0 = qa [gid * TC_QS ],x1 = qa [(gid + 8 )* TC_QS ]; 393const float x2 = qa [gid * TC_QS + 4 ],x3 = qa [(gid + 8 )* TC_QS + 4 ]; 394uint32_t ah [4 ],al [4 ]; 395ah [0 ]= tf32_hi (x0 );ah [1 ]= tf32_hi (x1 );ah [2 ]= tf32_hi (x2 );ah [3 ]= tf32_hi (x3 ); 396al [0 ]= tf32_hi (x0 - sycl::bit_cast < float > (ah [0 ])); 397al [1 ]= tf32_hi (x1 - sycl::bit_cast < float > (ah [1 ])); 398al [2 ]= tf32_hi (x2 - sycl::bit_cast < float > (ah [2 ])); 399al [3 ]= tf32_hi (x3 - sycl::bit_cast < float > (ah [3 ])); 400mma_tf32 (acc [h ],al ,bh ); 401mma_tf32 (acc [h ],ah ,bl ); 402mma_tf32 (acc [h ],ah ,bh ); 403 } 404 } 405// relu per head, heads added in order (as the warp kernel), written where the block completed for the query 406const int64_t bc = b0 + warp * 8 + 2 * tig ; 407#pragma unroll 408for (int half = 0 ;half < 2 ;++ half ) { 409const int qr = gid + half * 8 ; 410const int64_t qi = q0 + qr ; 411if (qi >=nq )continue ; 412const int nb = s_nbid [qr ]; 413#pragma unroll 414for (int j = 0 ;j < 2 ;++ j ) { 415const int64_t b = bc + j ; 416if (b >=nb || b >=max_blocks )continue ; 417float score = 0.0f ; 418#pragma unroll 419for (int h = 0 ;h < IDX_HEADS ;++ h ) { 420const float d = acc [h ][half * 2 + j ]; 421score += d > 0.0f ?d :0.0f ; 422 } 423out [qi * max_blocks + b ]= score ; 424 } 425 } 426 } 427} 428 429#if defined(__HIPCC__ ) 430// ---- gfx12 (RDNA4: gfx1200 / gfx1201) scorer on v_wmma_f32_16x16x16_bf16 (wave32). Same GEMM as above: for a tile of 16 431// queries, every block's score is sum over the 4 indexer heads of relu(q_h . k), K = 128. FP32-level accuracy from a 432// three-way bf16 split of both operands (x = hi + mid + lo EXACTLY - the top 8, next 8 and last 8 bits of the fp32 433// mantissa, so bf16's fp32-sized exponent range needs no scaling) and the six products of order <= 2, smallest first; 434// like the TF32 kernel it sums in another order than the warp kernel (not bitwise). The tail block n_bid is the warp 435// kernel's arithmetic (block_scores_tail_kernel). 436// D = A x B with A = 16 key blocks (row l%16 of a lane, k = 8*(l/16)+i), B = 16 queries (column l%16, same k): 437// a lane ends up with 8 consecutive blocks of ONE query, written as one run. No LDS for keys: a lane reads its 438// 32-byte slice of the key row from global (the 16 query tiles of a launch re-read them from L2); the queries are 439// split once per CTA into LDS. 440// gfx11 (RDNA3 / RDNA3.5) has the same instruction with another fragment layout: a lane holds all 16 k of its row 441// (A) or column (B) - lanes 16..31 repeat lanes 0..15 - and D[2i + l/16][l%16]; SEL_KL is the k per lane, SEL_KOFF(g) 442// the first, SEL_ROW(i, g) the D row of element i. Same products, same order per element as on gfx12. 443#if defined(__gfx1200__ )|| defined(__gfx1201__ ) 444#define STRATA_SEL_GFX12 1 445#define STRATA_SEL_GFX11 0 446#elif defined(__gfx1100__ )|| defined(__gfx1101__ )|| defined(__gfx1102__ )|| defined(__gfx1150__ )|| \ 447 defined(__gfx1151__ ) 448#define STRATA_SEL_GFX12 0 449#define STRATA_SEL_GFX11 1 450#else 451#define STRATA_SEL_GFX12 0 452#define STRATA_SEL_GFX11 0 453#endif 454#if STRATA_SEL_GFX11 455constexpr int SEL_KL = 16 ; 456#define SEL_KOFF (g ) 0 457#define SEL_ROW (i ,g ) (2 * (i) + (g)) 458#else 459constexpr int SEL_KL = 8 ; 460#define SEL_KOFF (g ) ((g) * 8) 461#define SEL_ROW (i ,g ) ((g) * 8 + (i)) 462#endif 463typedef short sel_s8 __attribute__((ext_vector_type (SEL_KL ))); 464typedef float sel_f8 __attribute__((ext_vector_type (8 ))); 465typedef uint32_t sel_u4 __attribute__((ext_vector_type (SEL_KL /2 ))); 466constexpr int WQT = 16 ;// queries per CTA (the N of one WMMA) 467constexpr int WITER = 4 ;// key tiles per warp (the CTA covers 4 warps * WITER * 16 blocks) 468constexpr int WQS = IDX_DIM + 8 ;// bf16 elements per LDS row: 272 bytes, conflict-free 16-byte reads 469 470__device__ __forceinline__ sel_f8 wmma_bf16 (const sel_s8 & a ,const sel_s8 & b ,const sel_f8 & c ) { 471#if STRATA_SEL_GFX12 472return __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32_gfx12 (a ,b ,c ); 473#elif STRATA_SEL_GFX11 474return __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32 (a ,b ,c ); 475#else 476/* unreachable on SYCL: the launcher refuses this device */ 477return c ; 478#endif 479} 480// the bf16 pieces of x as fp32 bit patterns whose upper 16 bits are the bf16 (lower 16 are zero) 481__device__ __forceinline__ void split3 (float x ,uint32_t & hi ,uint32_t & mid ,uint32_t & lo ) { 482hi = sycl::bit_cast < uint32_t > (x )& 0xffff0000u ; 483const float r1 = x - __uint_as_float (hi );// exact 484mid = sycl::bit_cast < uint32_t > (r1 )& 0xffff0000u ; 485lo = sycl::bit_cast < uint32_t > (r1 - __uint_as_float (mid ))& 0xffff0000u ;// exact: at most 8 significant bits left 486} 487__device__ __forceinline__ uint32_t pack_bf16x2 (uint32_t a ,uint32_t b ) {// low half = a's bf16, high half = b's 488#if STRATA_SEL_GFX12 || STRATA_SEL_GFX11 489return __builtin_amdgcn_perm (b ,a ,0x07060302u ); 490#else 491return (a >>16 ) | (b & 0xffff0000u ); 492#endif 493} 494 495__global__ void __launch_bounds__ (128 )block_scores_wmma_kernel (const float * __restrict__pooled , 496const float * __restrict__q_idx , 497const int32_t * __restrict__steps ,int64_t nq , 498int64_t max_blocks ,int64_t reach , 499float * __restrict__out ) { 500__shared__ __align__ (16 )uint16_t sq [3 ][IDX_HEADS ][WQT ][WQS ];// hi / mid / lo, [head][query][dim] 501__shared__ int s_nbid [WQT ]; 502const int t = threadIdx .x ,lane = t & 31 ,warp = t >>5 ,l16 = lane & 15 ,g = lane >>4 ; 503const int64_t q0 = (int64_t )blockIdx .y * WQT ; 504for (int i = t ;i < WQT * IDX_HEADS * IDX_DIM /4 ;i += 128 ) { 505const int row = i / (IDX_DIM /4 ),c = i % (IDX_DIM /4 ); 506const int qr = row /IDX_HEADS ,h = row %IDX_HEADS ; 507float4 v = make_float4 (0.f ,0.f ,0.f ,0.f ); 508if (q0 + qr < nq )v = reinterpret_cast < const float4 *> (q_idx + (q0 + qr )* IDX_HEADS * IDX_DIM )[h * (IDX_DIM /4 )+ c ]; 509const float x [4 ]= {v .x ,v .y ,v .z ,v .w }; 510uint32_t hb [4 ],mb [4 ],lb [4 ]; 511#pragma unroll 512for (int j = 0 ;j < 4 ;++ j )split3 (x [j ],hb [j ],mb [j ],lb [j ]); 513* reinterpret_cast < uint2 *> (& sq [0 ][h ][qr ][c * 4 ])= make_uint2 (pack_bf16x2 (hb [0 ],hb [1 ]),pack_bf16x2 (hb [2 ],hb [3 ])); 514* reinterpret_cast < uint2 *> (& sq [1 ][h ][qr ][c * 4 ])= make_uint2 (pack_bf16x2 (mb [0 ],mb [1 ]),pack_bf16x2 (mb [2 ],mb [3 ])); 515* reinterpret_cast < uint2 *> (& sq [2 ][h ][qr ][c * 4 ])= make_uint2 (pack_bf16x2 (lb [0 ],lb [1 ]),pack_bf16x2 (lb [2 ],lb [3 ])); 516 } 517if (t < WQT )s_nbid [t ]= q0 + t < nq ?steps [(q0 + t )* kStepCount + kStepNBid ] :0 ; 518__syncthreads (); 519int hi_nbid = 0 ; 520#pragma unroll 521for (int i = 0 ;i < WQT ;++ i )hi_nbid = max (hi_nbid ,s_nbid [i ]); 522const int64_t qi = q0 + l16 ; 523const int nb_q = s_nbid [l16 ]; 524for (int it = 0 ;it < WITER ;++ it ) { 525const int64_t b0 = (((int64_t )blockIdx .x * WITER + it )* 4 + warp )* 16 ; 526if (b0 >=reach || b0 >=hi_nbid )break ;// warp-uniform; later tiles start higher 527const int64_t row = b0 + l16 ; 528const bool rv = row < hi_nbid && row < max_blocks ; 529const float * kp = pooled + (rv ?row :0 )* IDX_DIM + SEL_KOFF (g ); 530// acc: the hi*hi products; cor: the five smaller ones (<= 2^-8 of it). Kept apart and added once at the end: a 531// correction summed into the big accumulator is rounded to ITS ulp at every one of the 48 steps (measured: 8e-7 532// of the score scale; apart, near the warp kernel's) 533sel_f8 acc [IDX_HEADS ],cor [IDX_HEADS ]; 534#pragma unroll 535for (int h = 0 ;h < IDX_HEADS ;++ h )acc [h ]= cor [h ]= sel_f8 {0.f ,0.f ,0.f ,0.f ,0.f ,0.f ,0.f ,0.f }; 536#pragma unroll 2 537for (int kk = 0 ;kk < IDX_DIM /16 ;++ kk ) { 538float x [SEL_KL ]; 539#pragma unroll 540for (int j = 0 ;j < SEL_KL /4 ;++ j ) { 541float4 kv = make_float4 (0.f ,0.f ,0.f ,0.f ); 542if (rv )kv = * reinterpret_cast < const float4 *> (kp + kk * 16 + 4 * j ); 543x [4 * j ]= kv .x ;x [4 * j + 1 ]= kv .y ;x [4 * j + 2 ]= kv .z ;x [4 * j + 3 ]= kv .w ; 544 } 545uint32_t hb [SEL_KL ],mb [SEL_KL ],lb [SEL_KL ]; 546#pragma unroll 547for (int j = 0 ;j < SEL_KL ;++ j )split3 (x [j ],hb [j ],mb [j ],lb [j ]); 548sel_u4 ah ,am ,al ; 549#pragma unroll 550for (int j = 0 ;j < SEL_KL /2 ;++ j ) { 551ah [j ]= pack_bf16x2 (hb [2 * j ],hb [2 * j + 1 ]); 552am [j ]= pack_bf16x2 (mb [2 * j ],mb [2 * j + 1 ]); 553al [j ]= pack_bf16x2 (lb [2 * j ],lb [2 * j + 1 ]); 554 } 555const sel_s8 Ah = __builtin_bit_cast (sel_s8 ,ah ),Am = __builtin_bit_cast (sel_s8 ,am ), 556Al = __builtin_bit_cast (sel_s8 ,al ); 557#pragma unroll 558for (int h = 0 ;h < IDX_HEADS ;++ h ) { 559const sel_s8 Bh = * reinterpret_cast < const sel_s8 *> (& sq [0 ][h ][l16 ][kk * 16 + SEL_KOFF (g )]); 560const sel_s8 Bm = * reinterpret_cast < const sel_s8 *> (& sq [1 ][h ][l16 ][kk * 16 + SEL_KOFF (g )]); 561const sel_s8 Bl = * reinterpret_cast < const sel_s8 *> (& sq [2 ][h ][l16 ][kk * 16 + SEL_KOFF (g )]); 562cor [h ]= wmma_bf16 (Al ,Bh ,cor [h ]); 563cor [h ]= wmma_bf16 (Ah ,Bl ,cor [h ]); 564cor [h ]= wmma_bf16 (Am ,Bm ,cor [h ]); 565cor [h ]= wmma_bf16 (Ah ,Bm ,cor [h ]); 566cor [h ]= wmma_bf16 (Am ,Bh ,cor [h ]); 567acc [h ]= wmma_bf16 (Ah ,Bh ,acc [h ]); 568 } 569 } 570// relu per head, heads added in order (as the warp kernel); this lane: query qi, blocks b0 + SEL_ROW(i, g) 571if (qi < nq ) { 572#pragma unroll 573for (int i = 0 ;i < 8 ;++ i ) { 574const int64_t b = b0 + SEL_ROW (i ,g ); 575if (b >=nb_q || b >=max_blocks )continue ; 576float score = 0.0f ; 577#pragma unroll 578for (int h = 0 ;h < IDX_HEADS ;++ h ) { 579const float d = acc [h ][i ]+ cor [h ][i ]; 580score += d > 0.0f ?d :0.0f ; 581 } 582out [qi * max_blocks + b ]= score ; 583 } 584 } 585 } 586} 587 588// the WMMA kernel needs gfx12 (gfx1200/gfx1201) or gfx11 (gfx110x/gfx115x: the other fragment layout) code objects 589bool sel_gfx12_device () { 590static int ok [64 ]= {};// per device: 0 unknown, 1 yes, 2 no 591int dev = 0 ; 592if (cudaGetDevice (& dev )!= cudaSuccess || dev < 0 || dev >=64 ) {cudaGetLastError ();return false; } 593if (ok [dev ]== 0 ) { 594cudaDeviceProp prop ; 595ok [dev ]= (cudaGetDeviceProperties (& prop ,dev )== cudaSuccess && 596 (std::strncmp (prop .gcnArchName ,"gfx1200" ,7 )== 0 || std::strncmp (prop .gcnArchName ,"gfx1201" ,7 )== 0 || 597 strata::kernels::gfx_arch_is_gfx11_wmma (prop .gcnArchName ))) 598 ?1 :2 ; 599cudaGetLastError (); 600 } 601return ok [dev ]== 1 ; 602} 603#endif // __HIPCC__ 604 605// the tail block n_bid of each query: exactly block_scores_kernel's arithmetic for that block 606__dpct_inline__ void block_scores_tail_kernel (const float * __restrict__dead , 607const float * __restrict__q_idx , 608const int32_t * __restrict__steps , 609int64_t max_blocks , 610float * __restrict__out ) { 611auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item < 3 > (); 612const int64_t qi = item_ct1 .get_group (2 ); 613const int32_t * st = steps + qi * kStepCount ; 614const int64_t n_kv = st [kStepNKv ],n_bid = st [kStepNBid ]; 615if (n_bid >=max_blocks )return ; 616const int lane = item_ct1 .get_local_id (2 )& 31 ; 617const sycl::float4 k4 = 618* reinterpret_cast < const sycl::float4 *> (dead + lane * 4 ); 619const float * q = q_idx + qi * IDX_HEADS * IDX_DIM + lane * 4 ; 620float score = 0.0f ; 621#pragma unroll 622for (int h = 0 ;h < IDX_HEADS ;++ h ) { 623const sycl::float4 q4 = 624* reinterpret_cast < const sycl::float4 *> (q + h * IDX_DIM ); 625float d = k4 .x ()* q4 .x ()+ k4 .y ()* q4 .y ()+ k4 .z ()* q4 .z ()+ 626k4 .w ()* q4 .w (); 627#pragma unroll 628/* 629DPCT1108: '__shfl_xor_sync' was migrated with the experimental 630feature masked sub_group function which may not be supported by all 631compilers or runtimes. You may need to adjust the code. 632*/ 633for (int o = 16 ;o > 0 ;o >>=1 )d += 634 dpct::experimental::permute_sub_group_by_xor ( 6350xffffffffu , sycl::ext::oneapi::this_work_item::get_sub_group (), 636d ,o ); 637score += d > 0.0f ?d :0.0f ; 638 } 639if (lane == 0 ) { 640if (n_kv %R != 0 )score += 1e9f ; 641out [qi * max_blocks + n_bid ]= score ; 642 } 643} 644 645// ---- the same top-k with each query's keys read once: 1,024 threads hold up to TK_PER consecutive blocks' keys in 646// registers (contexts up to 4 * 1024 * TK_PER cells), per-warp histograms, block-wide scans. The selection rule is 647// block_topk_kernel's (radix threshold, ties to the lowest index, cells ascending): identical ids. 648constexpr int TK_T = 1024 ; 649constexpr int TK_PER = 33 ; 650#if defined(__HIPCC__ ) 651// AMD (RDNA, wave32): a 1,024-thread block may use 192 VGPRs per lane, so the keys of 66 blocks per thread fit - contexts 652// up to 4 * 1024 * 66 = 270,336 cells (the 262,144 --max-context) keep the register kernel. NVIDIA's 64 registers per 653// thread at 1,024 threads allow only TK_PER. 654constexpr int TK_PER_MAX = 66 ; 655#else 656constexpr int TK_PER_MAX = TK_PER ; 657#endif 658 659__dpct_inline__ int block_excl_scan (int v ,int * s_warp ,int & total ) { 660auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item < 3 > (); 661const int lane = item_ct1 .get_local_id (2 )& 31 , 662warp = item_ct1 .get_local_id (2 ) >>5 ; 663int x = v ; 664#pragma unroll 665for (int o = 1 ;o < 32 ;o <<=1 ) { 666/* 667DPCT1108: '__shfl_up_sync' was migrated with the experimental feature 668masked sub_group function which may not be supported by all compilers or 669runtimes. You may need to adjust the code. 670*/ 671const int y = dpct::experimental::shift_sub_group_right ( 6720xffffffffu , sycl::ext::oneapi::this_work_item::get_sub_group (),x , 673o ); 674if (lane >=o )x += y ; 675 } 676if (lane == 31 )s_warp [warp ]= x ; 677/* 678DPCT1065: Consider replacing sycl::nd_item::barrier() with 679sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better 680performance if there is no access to global memory. 681*/ 682item_ct1 .barrier (); 683if (warp == 0 ) { 684int w = s_warp [lane ]; 685int z = w ; 686#pragma unroll 687for (int o = 1 ;o < 32 ;o <<=1 ) { 688/* 689DPCT1108: '__shfl_up_sync' was migrated with the experimental 690feature masked sub_group function which may not be supported by all 691compilers or runtimes. You may need to adjust the code. 692*/ 693const int y = dpct::experimental::shift_sub_group_right ( 6940xffffffffu , sycl::ext::oneapi::this_work_item::get_sub_group (), 695z ,o ); 696if (lane >=o )z += y ; 697 } 698s_warp [lane ]= z - w ;// exclusive per warp 699if (lane == 31 )s_warp [32 ]= z ;// total 700 } 701/* 702DPCT1065: Consider replacing sycl::nd_item::barrier() with 703sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better 704performance if there is no access to global memory. 705*/ 706item_ct1 .barrier (); 707const int r = s_warp [warp ]+ x - v ; 708total = s_warp [32 ]; 709/* 710DPCT1065: Consider replacing sycl::nd_item::barrier() with 711sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better 712performance if there is no access to global memory. 713*/ 714item_ct1 .barrier (); 715return r ; 716} 717 718template < int PER > 719/* 720DPCT1110: The total declared local variable size in device function 721block_topk_reg_kernel exceeds 128 bytes and may cause high register pressure. 722Consult with your hardware vendor to find the total register size available and 723adjust the code, or use smaller sub-group size to avoid high register pressure. 724*/ 725__dpct_inline__ void block_topk_reg_kernel (const float * __restrict__scores , 726const int32_t * __restrict__steps , 727int64_t max_blocks ,int64_t cap , 728int32_t * __restrict__ids ) { 729auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item < 3 > (); 730auto & hist = 731* sycl::ext::oneapi::group_local_memory_for_overwrite < int [TK_T /32 ][256 ]> ( 732 sycl::ext::oneapi::this_work_item::get_work_group < 3 > ()); 733auto & s_warp = 734* sycl::ext::oneapi::group_local_memory_for_overwrite < int [33 ]> ( 735 sycl::ext::oneapi::this_work_item::get_work_group < 3 > ()); 736auto & s_digit = * sycl::ext::oneapi::group_local_memory_for_overwrite < int > ( 737 sycl::ext::oneapi::this_work_item::get_work_group < 3 > ()); 738auto & s_above = * sycl::ext::oneapi::group_local_memory_for_overwrite < int > ( 739 sycl::ext::oneapi::this_work_item::get_work_group < 3 > ()); 740const int64_t qi = item_ct1 .get_group (2 ); 741const int32_t * st = steps + qi * kStepCount ; 742const int64_t n_kv = st [kStepNKv ],n_bid = st [kStepNBid ],width = st [kStepWidth ]; 743int32_t * out = ids + qi * cap ; 744const int t = item_ct1 .get_local_id (2 ),lane = t & 31 ,warp = t >>5 ; 745if (n_kv <=width ) { 746#pragma unroll 747for (int64_t j = t ;j < n_kv ;j += TK_T )out [j ]= (int32_t )j ; 748return ; 749 } 750const float * sc = scores + qi * max_blocks ; 751const int64_t nb = n_bid + 1 ; 752const int64_t per = (nb + TK_T - 1 ) /TK_T ;// <= PER (the caller checks) 753const int64_t b0 = (int64_t )t * per ,b1 = (b0 + per < nb ) ?b0 + per :nb ; 754uint32_t key [PER ]; 755#pragma unroll 756for (int j = 0 ;j < PER ;++ j )key [j ]= (b0 + j < b1 ) ?order_key (sc [b0 + j ]) :0u ; 757auto weight = [& ](int64_t b )-> int {return b < n_bid ?R : (int ) (n_kv - n_bid * R ); }; 758uint32_t prefix = 0 ; 759int above = 0 ; 760for (int shift = 24 ;shift >=0 ;shift -= 8 ) { 761#pragma unroll 762for (int i = lane ;i < 256 ;i += 32 )hist [warp ][i ]= 0 ; 763 sycl::group_barrier (sycl::ext::oneapi::this_work_item::get_sub_group ()); 764const uint32_t hi_mask = shift == 24 ?0u : (0xffffffffu << (shift + 8 )); 765#pragma unroll 766for (int j = 0 ;j < PER ;++ j ) { 767const int64_t b = b0 + j ; 768if (b >=b1 )break ; 769const int w = weight (b ); 770if (w == 0 )continue ; 771if ((key [j ]& hi_mask )== (prefix & hi_mask )) 772 dpct::atomic_fetch_add < 773 sycl::access::address_space::generic_space > ( 774& hist [warp ][(key [j ] >>shift )& 255 ],w ); 775 } 776/* 777DPCT1118: SYCL group functions and algorithms must be encountered in 778converged control flow. You may need to adjust the code. 779*/ 780/* 781DPCT1065: Consider replacing sycl::nd_item::barrier() with 782sycl::nd_item::barrier(sycl::access::fence_space::local_space) for 783better performance if there is no access to global memory. 784*/ 785item_ct1 .barrier (); 786if (t < 256 ) {// fold the warps' histograms into warp 0's 787int s = 0 ; 788#pragma unroll 789for (int w2 = 0 ;w2 < TK_T /32 ;++ w2 )s += hist [w2 ][t ]; 790hist [0 ][t ]= s ; 791 } 792/* 793DPCT1118: SYCL group functions and algorithms must be encountered in 794converged control flow. You may need to adjust the code. 795*/ 796/* 797DPCT1065: Consider replacing sycl::nd_item::barrier() with 798sycl::nd_item::barrier(sycl::access::fence_space::local_space) for 799better performance if there is no access to global memory. 800*/ 801item_ct1 .barrier (); 802if (t == 0 ) { 803int cum = above ,d = 255 ; 804#pragma unroll 805for (;d > 0 ;-- d ) { 806if (cum + hist [0 ][d ] >=width )break ; 807cum += hist [0 ][d ]; 808 } 809s_digit = d ; 810s_above = cum ; 811 } 812/* 813DPCT1118: SYCL group functions and algorithms must be encountered in 814converged control flow. You may need to adjust the code. 815*/ 816/* 817DPCT1065: Consider replacing sycl::nd_item::barrier() with 818sycl::nd_item::barrier(sycl::access::fence_space::local_space) for 819better performance if there is no access to global memory. 820*/ 821item_ct1 .barrier (); 822prefix |= (uint32_t )s_digit <<shift ; 823above = s_above ; 824/* 825DPCT1118: SYCL group functions and algorithms must be encountered in 826converged control flow. You may need to adjust the code. 827*/ 828/* 829DPCT1065: Consider replacing sycl::nd_item::barrier() with 830sycl::nd_item::barrier(sycl::access::fence_space::local_space) for 831better performance if there is no access to global memory. 832*/ 833item_ct1 .barrier (); 834 } 835const uint32_t thr = prefix ; 836const int64_t eq_budget = width - above ; 837int gt = 0 ,eq = 0 ; 838#pragma unroll 839for (int j = 0 ;j < PER ;++ j ) { 840const int64_t b = b0 + j ; 841if (b >=b1 )break ; 842const int w = weight (b ); 843if (w == 0 )continue ; 844if (key [j ]> thr )gt += w ; 845else if (key [j ]== thr )eq += w ; 846 } 847int tot ; 848const int eq_before = block_excl_scan (eq ,s_warp ,tot ); 849int64_t my_eq = eq_budget - eq_before ; 850if (my_eq < 0 )my_eq = 0 ; 851if (my_eq > eq )my_eq = eq ; 852const int sel = gt + (int )my_eq ; 853int64_t wpos = block_excl_scan (sel ,s_warp ,tot ); 854int64_t eq_left = my_eq ; 855#pragma unroll 856for (int j = 0 ;j < PER ;++ j ) { 857const int64_t b = b0 + j ; 858if (b >=b1 )break ; 859const int w = weight (b ); 860if (w == 0 )continue ; 861if (key [j ]> thr ) { 862#pragma unroll 863for (int c = 0 ;c < w ;++ c )out [wpos ++ ]= (int32_t )(b * R + c ); 864 }else if (key [j ]== thr ) { 865#pragma unroll 866for (int c = 0 ;c < w && eq_left > 0 ;++ c ,-- eq_left ) 867out [wpos ++ ]= (int32_t )(b * R + c ); 868 } 869 } 870} 871 872#if !defined(__HIPCC__ ) 873// ---- a query with more blocks than the register kernel holds (contexts past 4 * 1024 * TK_PER cells): the register 874// kernel's threads, per-warp histograms and warp scans, with each key read from memory again on every pass. A 875// histogram has no order, so on the four radix passes thread t reads blocks t, t + 1024, ...: a warp reads 32 876// neighbours at a time. The cells are emitted ascending in the order (warp, row, lane): warp w holds the `per` rows 877// of 32 consecutive blocks from block w * 32 * per. block_topk_kernel's selection rule (radix threshold, ties to the 878// lowest index): identical ids. 879/* 880DPCT1110: The total declared local variable size in device function 881block_topk_wide_kernel exceeds 128 bytes and may cause high register pressure. 882Consult with your hardware vendor to find the total register size available and 883adjust the code, or use smaller sub-group size to avoid high register pressure. 884*/ 885__dpct_inline__ void block_topk_wide_kernel (const float * __restrict__scores , 886const int32_t * __restrict__steps , 887int64_t max_blocks ,int64_t cap , 888int32_t * __restrict__ids ) { 889auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item < 3 > (); 890auto & hist = 891* sycl::ext::oneapi::group_local_memory_for_overwrite < int [TK_T /32 ][256 ]> ( 892 sycl::ext::oneapi::this_work_item::get_work_group < 3 > ()); 893auto & s_gt = 894* sycl::ext::oneapi::group_local_memory_for_overwrite < int [TK_T /32 ]> ( 895 sycl::ext::oneapi::this_work_item::get_work_group < 3 > ()); 896auto & s_eq = 897* sycl::ext::oneapi::group_local_memory_for_overwrite < int [TK_T /32 ]> ( 898 sycl::ext::oneapi::this_work_item::get_work_group < 3 > ()); 899auto & s_digit = * sycl::ext::oneapi::group_local_memory_for_overwrite < int > ( 900 sycl::ext::oneapi::this_work_item::get_work_group < 3 > ()); 901auto & s_above = * sycl::ext::oneapi::group_local_memory_for_overwrite < int > ( 902 sycl::ext::oneapi::this_work_item::get_work_group < 3 > ()); 903const int64_t qi = item_ct1 .get_group (2 ); 904const int32_t * st = steps + qi * kStepCount ; 905const int64_t n_kv = st [kStepNKv ],n_bid = st [kStepNBid ],width = st [kStepWidth ]; 906int32_t * out = ids + qi * cap ; 907const int t = item_ct1 .get_local_id (2 ),lane = t & 31 ,warp = t >>5 ; 908if (n_kv <=width ) { 909#pragma unroll 910for (int64_t j = t ;j < n_kv ;j += TK_T )out [j ]= (int32_t )j ; 911return ; 912 } 913const float * sc = scores + qi * max_blocks ; 914const int64_t nb = n_bid + 1 ; 915const int64_t per = (nb + TK_T - 1 ) /TK_T ;// rows of 32 blocks per warp 916auto weight = [& ](int64_t b )-> int {return b < n_bid ?R : (int ) (n_kv - n_bid * R ); }; 917uint32_t prefix = 0 ; 918int above = 0 ; 919for (int shift = 24 ;shift >=0 ;shift -= 8 ) { 920#pragma unroll 921for (int i = lane ;i < 256 ;i += 32 )hist [warp ][i ]= 0 ; 922 sycl::group_barrier (sycl::ext::oneapi::this_work_item::get_sub_group ()); 923const uint32_t hi_mask = shift == 24 ?0u : (0xffffffffu << (shift + 8 )); 924for (int64_t b = t ;b < nb ;b += TK_T ) { 925const int w = weight (b ); 926if (w == 0 )continue ; 927const uint32_t k = order_key (sc [b ]); 928if ((k & hi_mask )== (prefix & hi_mask )) dpct::atomic_fetch_add < 929 sycl::access::address_space::generic_space > ( 930& hist [warp ][(k >>shift )& 255 ],w ); 931 } 932/* 933DPCT1118: SYCL group functions and algorithms must be encountered in 934converged control flow. You may need to adjust the code. 935*/ 936/* 937DPCT1065: Consider replacing sycl::nd_item::barrier() with 938sycl::nd_item::barrier(sycl::access::fence_space::local_space) for 939better performance if there is no access to global memory. 940*/ 941item_ct1 .barrier (); 942if (t < 256 ) {// fold the warps' histograms into warp 0's 943int sum = 0 ; 944#pragma unroll 945for (int w2 = 0 ;w2 < TK_T /32 ;++ w2 )sum += hist [w2 ][t ]; 946hist [0 ][t ]= sum ; 947 } 948/* 949DPCT1118: SYCL group functions and algorithms must be encountered in 950converged control flow. You may need to adjust the code. 951*/ 952/* 953DPCT1065: Consider replacing sycl::nd_item::barrier() with 954sycl::nd_item::barrier(sycl::access::fence_space::local_space) for 955better performance if there is no access to global memory. 956*/ 957item_ct1 .barrier (); 958if (t == 0 ) { 959int cum = above ,d = 255 ; 960#pragma unroll 961for (;d > 0 ;-- d ) { 962if (cum + hist [0 ][d ] >=width )break ; 963cum += hist [0 ][d ]; 964 } 965s_digit = d ; 966s_above = cum ; 967 } 968/* 969DPCT1118: SYCL group functions and algorithms must be encountered in 970converged control flow. You may need to adjust the code. 971*/ 972/* 973DPCT1065: Consider replacing sycl::nd_item::barrier() with 974sycl::nd_item::barrier(sycl::access::fence_space::local_space) for 975better performance if there is no access to global memory. 976*/ 977item_ct1 .barrier (); 978prefix |= (uint32_t )s_digit <<shift ; 979above = s_above ; 980/* 981DPCT1118: SYCL group functions and algorithms must be encountered in 982converged control flow. You may need to adjust the code. 983*/ 984/* 985DPCT1065: Consider replacing sycl::nd_item::barrier() with 986sycl::nd_item::barrier(sycl::access::fence_space::local_space) for 987better performance if there is no access to global memory. 988*/ 989item_ct1 .barrier (); 990 } 991const uint32_t thr = prefix ; 992const int eq_budget = (int ) (width - above );// cells equal to thr that fit, lowest index first 993const int64_t w0 = (int64_t )warp * 32 * per ; 994int gt = 0 ,eq = 0 ; 995for (int64_t b = w0 + lane ;b < nb && b < w0 + 32 * per ;b += 32 ) { 996const int w = weight (b ); 997if (w == 0 )continue ; 998const uint32_t k = order_key (sc [b ]); 999if (k > thr )gt += w ; 1000else if (k == thr )eq += w ; 1001 } 1002#pragma unroll 1003for (int o = 16 ;o > 0 ;o >>=1 ) { 1004/* 1005DPCT1108: '__shfl_xor_sync' was migrated with the experimental 1006feature masked sub_group function which may not be supported by all 1007compilers or runtimes. You may need to adjust the code. 1008*/ 1009gt += dpct::experimental::permute_sub_group_by_xor ( 10100xffffffffu , sycl::ext::oneapi::this_work_item::get_sub_group (),gt , 1011o ); 1012/* 1013DPCT1108: '__shfl_xor_sync' was migrated with the experimental 1014feature masked sub_group function which may not be supported by all 1015compilers or runtimes. You may need to adjust the code. 1016*/ 1017eq += dpct::experimental::permute_sub_group_by_xor ( 10180xffffffffu , sycl::ext::oneapi::this_work_item::get_sub_group (),eq , 1019o ); 1020 } 1021if (lane == 0 ) {s_gt [warp ]= gt ;s_eq [warp ]= eq ; } 1022/* 1023DPCT1065: Consider replacing sycl::nd_item::barrier() with 1024sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better 1025performance if there is no access to global memory. 1026*/ 1027item_ct1 .barrier (); 1028if (t == 0 ) {// per warp: the selected cells and the tied cells before it 1029int eb = 0 ,sb = 0 ; 1030for (int w2 = 0 ;w2 < TK_T /32 ;++ w2 ) { 1031const int g2 = s_gt [w2 ],e2 = s_eq [w2 ]; 1032const int take = eq_budget - eb < 0 ?0 : (eq_budget - eb > e2 ?e2 :eq_budget - eb ); 1033s_gt [w2 ]= sb ; 1034s_eq [w2 ]= eb ; 1035sb += g2 + take ; 1036eb += e2 ; 1037 } 1038 } 1039/* 1040DPCT1065: Consider replacing sycl::nd_item::barrier() with 1041sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better 1042performance if there is no access to global memory. 1043*/ 1044item_ct1 .barrier (); 1045int run_sel = s_gt [warp ],run_eq = s_eq [warp ]; 1046for (int64_t r0 = w0 ;r0 < nb && r0 < w0 + 32 * per ;r0 += 32 ) { 1047const int64_t b = r0 + lane ; 1048const int w = b < nb ?weight (b ) :0 ; 1049const uint32_t k = w ?order_key (sc [b ]) :0u ; 1050const int my_gt = (w && k > thr ) ?w :0 ,my_eq = (w && k == thr ) ?w :0 ; 1051if (sycl::reduce_over_group ( 1052 sycl::ext::oneapi::this_work_item::get_sub_group (), 1053 (0xffffffffu & 1054 (0x1 << sycl::ext::oneapi::this_work_item::get_sub_group () 1055 .get_local_linear_id ()))&& 1056 (my_gt |my_eq )!= 0 1057 ? (0x1 << sycl::ext::oneapi::this_work_item::get_sub_group () 1058 .get_local_linear_id ()) 1059 :0 , 1060 sycl::ext::oneapi::plus <> ())== 10610u )continue ;// a row without a selected block 1062int pe = my_eq ;// tied cells up to and with this lane 1063#pragma unroll 1064for (int o = 1 ;o < 32 ;o <<=1 ) { 1065/* 1066DPCT1108: '__shfl_up_sync' was migrated with the experimental 1067feature masked sub_group function which may not be supported by all 1068compilers or runtimes. You may need to adjust the code. 1069*/ 1070const int y = dpct::experimental::shift_sub_group_right ( 10710xffffffffu , sycl::ext::oneapi::this_work_item::get_sub_group (), 1072pe ,o ); 1073if (lane >=o )pe += y ; 1074 } 1075const int left = eq_budget - (run_eq + pe - my_eq ); 1076const int take = left < 0 ?0 : (left > my_eq ?my_eq :left ); 1077const int my_sel = my_gt + take ; 1078int ps = my_sel ; 1079#pragma unroll 1080for (int o = 1 ;o < 32 ;o <<=1 ) { 1081/* 1082DPCT1108: '__shfl_up_sync' was migrated with the experimental 1083feature masked sub_group function which may not be supported by all 1084compilers or runtimes. You may need to adjust the code. 1085*/ 1086const int y = dpct::experimental::shift_sub_group_right ( 10870xffffffffu , sycl::ext::oneapi::this_work_item::get_sub_group (), 1088ps ,o ); 1089if (lane >=o )ps += y ; 1090 } 1091int32_t * dst = out + run_sel + ps - my_sel ; 1092#pragma unroll 1093for (int c = 0 ;c < my_sel ;++ c )dst [c ]= (int32_t )(b * R + c ); 1094/* 1095DPCT1108: '__shfl_sync' was migrated with the experimental feature 1096masked sub_group function which may not be supported by all compilers or 1097runtimes. You may need to adjust the code. 1098*/ 1099run_eq += dpct::experimental::select_from_sub_group ( 11000xffffffffu , sycl::ext::oneapi::this_work_item::get_sub_group (),pe , 110131 ); 1102/* 1103DPCT1108: '__shfl_sync' was migrated with the experimental feature 1104masked sub_group function which may not be supported by all compilers or 1105runtimes. You may need to adjust the code. 1106*/ 1107run_sel += dpct::experimental::select_from_sub_group ( 11080xffffffffu , sycl::ext::oneapi::this_work_item::get_sub_group (),ps , 110931 ); 1110 } 1111} 1112#endif 1113 1114 1115// Block scores with every key block read ONCE for all of a call's queries (block_scores_kernel's grid is 1116// (max_blocks / 8) x nq: ~24,600 mostly-idle blocks per layer at a decode window, each key re-read per query). A fixed 1117// grid strides over the blocks; per (block, query) the same arithmetic in the same order as block_scores_kernel. 1118// qsa_block_scores takes it for every call without an active-block count and at most MQ queries: the captured decode 1119// window, the uncaptured decode, and prefill's pooled16 call. 1120constexpr int MQ = 8 ; 1121/* 1122DPCT1110: The total declared local variable size in device function 1123block_scores_multi_kernel exceeds 128 bytes and may cause high register 1124pressure. Consult with your hardware vendor to find the total register size 1125available and adjust the code, or use smaller sub-group size to avoid high 1126register pressure. 1127*/ 1128__dpct_inline__ void block_scores_multi_kernel ( 1129const float * __restrict__pooled ,const float * __restrict__dead , 1130const float * __restrict__q_idx ,const int32_t * __restrict__steps ,int nq , 1131int64_t max_blocks ,float * __restrict__out ,bool early_exit ,QsaScoreRows srow = {}) { 1132auto item_ct1 = sycl::ext::oneapi::this_work_item:: get_nd_item < 3 > (); 1133auto & qs = * sycl::ext::oneapi:: group_local_memory_for_overwrite < 1134float[ MQ * IDX_HEADS * IDX_DIM ] > ( 1135sycl::ext::oneapi::this_work_item:: get_work_group < 3 > ()); 1136auto & s_nkv = 1137* sycl::ext::oneapi:: group_local_memory_for_overwrite < int64_t[ MQ ] > ( 1138sycl::ext::oneapi::this_work_item:: get_work_group < 3 > ()); 1139auto & s_nbid = 1140* sycl::ext::oneapi:: group_local_memory_for_overwrite < int64_t[ MQ ] > ( 1141sycl::ext::oneapi::this_work_item:: get_work_group < 3 > ()); 1142if (! early_exit ) 1143#pragma unroll 1144for (int i = item_ct1 . get_local_id ( 2 ); i < nq * IDX_HEADS * IDX_DIM ; 1145i += item_ct1 . get_local_range ( 2 )) qs [ i ] = q_idx [ i ]; 1146if ( item_ct1 . get_local_id ( 2 ) < nq ) { 1147s_nkv [ item_ct1 . get_local_id ( 2 )] = 1148steps [ item_ct1 . get_local_id ( 2 ) * kStepCount + kStepNKv ]; 1149s_nbid [ item_ct1 . get_local_id ( 2 )] = 1150steps [ item_ct1 . get_local_id ( 2 ) * kStepCount + kStepNBid ]; 1151} 1152item_ct1 . barrier (sycl::access::fence_space:: local_space ); 1153int64_t top = 0 ; 1154#pragma unroll 1155for (int q = 0 ; q < nq ; ++ q ) top = s_nbid [ q ] > top ? s_nbid [ q ] : top ; 1156if ( early_exit ) { 1157// (#783, stuchapin909) a CTA whose first block is past the batch's largest n_bid has no work: the grid is a 1158// fixed 256 CTAs and a decode window reaches only a few of them, so those return before staging the queries. 1159// Every thread of the CTA takes the same branch (top and blockIdx are CTA-uniform), so the barrier is safe. 1160if ((int64_t) item_ct1 . get_group ( 2 ) * SCORE_WARPS > top ) return ; 1161#pragma unroll 1162for (int i = item_ct1 . get_local_id ( 2 ); i < nq * IDX_HEADS * IDX_DIM ; 1163i += item_ct1 . get_local_range ( 2 )) qs [ i ] = q_idx [ i ]; 1164/* 1165DPCT1118: SYCL group functions and algorithms must be encountered in 1166converged control flow. You may need to adjust the code. 1167*/ 1168item_ct1 . barrier (sycl::access::fence_space:: local_space ); 1169} 1170const int lane = item_ct1 . get_local_id ( 2 ) & 31 ; 1171const int64_t wstride = (int64_t) item_ct1 . get_group_range ( 2 ) * SCORE_WARPS ; 1172for (int64_t b = (int64_t) item_ct1 . get_group ( 2 ) * SCORE_WARPS + 1173( item_ct1 . get_local_id ( 2 ) >> 5 ); 1174b <= top && b < max_blocks ; b += wstride ) { 1175// srow.n > 0: each query reads its own sequence's keys; else one set of keys for every query 1176const bool own = srow . n > 0 ; 1177const sycl::float4 kp = own ? sycl::float4{} : * reinterpret_cast < const sycl::float4 *> ( 1178pooled + b * IDX_DIM + lane * 4 ); 1179const sycl::float4 kd = own ? sycl::float4{} : 1180* reinterpret_cast < const sycl::float4 *> ( dead + lane * 4 ); 1181for (int qi = 0 ; qi < nq ; ++ qi ) { 1182const int64_t n_bid = s_nbid [ qi ]; 1183if ( b > n_bid ) continue ; 1184const sycl::float4 k4 = ! own ? (( b == n_bid ) ? kd : kp ) 1185: ( b == n_bid ) ? * reinterpret_cast < const sycl::float4 *> ( srow . dead [ qi ] + lane * 4 ) 1186: * reinterpret_cast < const sycl::float4 *> ( srow . pooled [ qi ] + b * IDX_DIM + lane * 4 ); 1187const float * q = qs + qi * IDX_HEADS * IDX_DIM + lane * 4 ; 1188float score = 0.0f ; 1189#pragma unroll 1190for (int h = 0 ; h < IDX_HEADS ; ++ h ) { 1191const sycl::float4 q4 = 1192* reinterpret_cast < const sycl::float4 *> ( q + h * IDX_DIM ); 1193float d = k4 . x () * q4 . x () + k4 . y () * q4 . y () + k4 . z () * q4 . z () + 1194k4 . w () * q4 . w (); 1195#pragma unroll 1196/* 1197DPCT1108: '__shfl_xor_sync' was migrated with the 1198experimental feature masked sub_group function which may not be 1199supported by all compilers or runtimes. You may need to adjust 1200the code. 1201*/ 1202for (int o = 16 ; o > 0 ; o >>= 1 ) d += 1203dpct::experimental:: permute_sub_group_by_xor ( 12040xffffffffu , 1205sycl::ext::oneapi::this_work_item:: get_sub_group (), d , 1206o ); 1207score += d > 0.0f ? d : 0.0f ; 1208} 1209if ( lane == 0 ) { 1210if ( b == n_bid && s_nkv [ qi ] % R != 0 ) score += 1e9f ; 1211out [ qi * max_blocks + b ] = score ; 1212} 1213} 1214} 1215} 1216 1217#if !defined( __HIPCC__ ) 1218// ---- the decode top-k on a thread-block cluster (sm_90+; S19). One CTA per query (block_topk_reg_kernel, or 1219// block_topk_kernel above 33,792 blocks: a --max-context over ~135K) makes four radix passes and two scans over up to 1220// 65,538 blocks on ONE SM while the rest of the GPU idles - a decode window has 1-5 queries. Here a cluster of CL_N 1221// CTAs shares a query: CTA r holds the keys of blocks [r * per, (r + 1) * per) in shared memory, builds the digit 1222// histogram of its keys, and PUSHES it into slot r of every CTA's `hin` (distributed shared memory); after one cluster 1223// barrier each CTA sums the CL_N slots itself, so all of them take the same digit. The emit pass needs each CTA's 1224// cells above / at the threshold: pushed the same way, then each CTA offsets its own by the ranks before it. 1225// RTX 5070, per call at capacity = context (decode_cluster_parity --bench): 21.9 -> 15.6 us at 32K, 58 -> 18 at 128K, 1226// 200 -> 22 at 262K (the one-CTA kernels' digit search was serial, too: one thread over 256 bins per pass). 1227// 1228// IDENTICAL IDS, by construction rather than by luck: the threshold thr (the width-th largest key, cells counted with 1229// their weights) and `above` (cells with a larger key) are pure functions of the multiset of (key, weight) - integer 1230// histograms, summed in any order - and the digit rule is block_topk_kernel's, written as a scan (the largest digit d 1231// whose cells at or above it reach `need`; 0 when none). The cells emitted are then fixed: every cell of a block with 1232// key > thr, and the first eq_budget = width - above cells at thr in ascending order (a block at thr may be cut), 1233// written in ascending cell order. Position of a thread's first cell = (cells above thr before it) + min(cells at thr 1234// before it, eq_budget): the telescoped sum of the reference's per-thread clamp. NaN keys are 0 (order_key) as there. 1235// 1236// Barriers: barrier.cluster arrive / wait (each CTA's threads all take part; it also orders the CTA's own shared 1237// memory, so it doubles as __syncthreads). Phase 0 is a relaxed arrive at entry, waited before the first remote store 1238// (a CTA's shared memory exists once it runs). Pushes go out before the arrive that releases them, and nothing reads 1239// another CTA's memory after the last wait - so a CTA may exit without a closing barrier (a wait counts the threads 1240// that have not exited). `hin` alternates by pass parity: CTA x reads slot buffer p&1 in pass p before arriving at 1241// pass p+1's barrier, and nobody writes buffer p&1 again (pass p+2) before waiting on that barrier. 1242constexpr int CL_N = 8 ; // CTAs per query (the portable cluster size) 1243constexpr int CL_T = 1024 ; // threads per CTA 1244constexpr int CL_MAXQ = 16 ; // larger calls (prefill sub-batches) fill the GPU with one CTA per query already 1245#if defined( DPCT_COMPATIBILITY_TEMP ) && DPCT_COMPATIBILITY_TEMP >= 900 1246#define STRATA_SEL_CLUSTER 1 1247#else 1248#define STRATA_SEL_CLUSTER 0 // an older target's code is a trap; qsa_block_topk_cluster never launches it there 1249#endif 1250 1251#if STRATA_SEL_CLUSTER 1252__dpct_inline__ void cl_arrive_relaxed () { 1253/* 1254DPCT1053: Migration of device assembly code is not supported. 1255*/ 1256asm volatile ( "barrier.cluster.arrive.relaxed.aligned;\n" ::: "memory" ); 1257} 1258/* 1259DPCT1053: Migration of device assembly code is not supported. 1260*/ 1261__dpct_inline__ void cl_arrive () { 1262asm volatile ( "barrier.cluster.arrive.release.aligned;\n" :: : "memory" ); 1263} 1264/* 1265DPCT1053: Migration of device assembly code is not supported. 1266*/ 1267__dpct_inline__ void cl_wait () { 1268asm volatile ( "barrier.cluster.wait.acquire.aligned;\n" :: : "memory" ); 1269} 1270__dpct_inline__ unsigned cl_rank () { 1271unsigned r ; 1272/* 1273DPCT1053: Migration of device assembly code is not supported. 1274*/ 1275asm volatile ( "mov.u32 %0, %%cluster_ctarank;\n" : "=r" ( r )); 1276return r ; 1277} 1278template < typename T > 1279__dpct_inline__ T * cl_map (T * p , 1280unsigned rank ) { // p in CTA `rank`'s shared memory 1281uint64_t o ; 1282/* 1283DPCT1053: Migration of device assembly code is not supported. 1284*/ 1285asm volatile ( "mapa.u64 %0, %1, %2;\n" 1286: "=l" ( o ) 1287: "l" ((uint64_t) p ), "r" ( rank )); 1288return reinterpret_cast < T *> ( o ); 1289} 1290// exclusive block scan of a 64-bit value over CL_T threads; `total` = the CTA's sum 1291__dpct_inline__ unsigned long long cl_excl_scan64 (unsigned long long v , 1292unsigned long long * s_warp , 1293unsigned long long & total ) { 1294auto item_ct1 = sycl::ext::oneapi::this_work_item:: get_nd_item < 3 > (); 1295const int lane = item_ct1 . get_local_id ( 2 ) & 31 , 1296warp = item_ct1 . get_local_id ( 2 ) >> 5 ; 1297unsigned long long x = v ; 1298#pragma unroll 1299for (int o = 1 ; o < 32 ; o <<= 1 ) { 1300/* 1301DPCT1108: '__shfl_up_sync' was migrated with the experimental feature 1302masked sub_group function which may not be supported by all compilers or 1303runtimes. You may need to adjust the code. 1304*/ 1305const unsigned long long y = dpct::experimental:: shift_sub_group_right ( 13060xffffffffu , sycl::ext::oneapi::this_work_item:: get_sub_group (), x , 1307o ); 1308if ( lane >= o ) x += y ; 1309} 1310if ( lane == 31 ) s_warp [ warp ] = x ; 1311/* 1312DPCT1065: Consider replacing sycl::nd_item::barrier() with 1313sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better 1314performance if there is no access to global memory. 1315*/ 1316item_ct1 . barrier (); 1317if ( warp == 0 ) { 1318const unsigned long long w = s_warp [ lane ]; 1319unsigned long long z = w ; 1320#pragma unroll 1321for (int o = 1 ; o < 32 ; o <<= 1 ) { 1322/* 1323DPCT1108: '__shfl_up_sync' was migrated with the experimental 1324feature masked sub_group function which may not be supported by all 1325compilers or runtimes. You may need to adjust the code. 1326*/ 1327const unsigned long long y = 1328dpct::experimental:: shift_sub_group_right ( 13290xffffffffu , 1330sycl::ext::oneapi::this_work_item:: get_sub_group (), z , o ); 1331if ( lane >= o ) z += y ; 1332} 1333s_warp [ lane ] = z - w ; 1334if ( lane == 31 ) s_warp [ 32 ] = z ; 1335} 1336/* 1337DPCT1065: Consider replacing sycl::nd_item::barrier() with 1338sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better 1339performance if there is no access to global memory. 1340*/ 1341item_ct1 . barrier (); 1342total = s_warp [ 32 ]; 1343return s_warp [ warp ] + x - v ; 1344} 1345#endif 1346 1347// grid (CL_N, nq), cluster (CL_N, 1, 1), CL_T threads, dynamic shared memory: ceil(max_blocks / CL_N) keys 1348/* 1349DPCT1110: The total declared local variable size in device function 1350block_topk_cluster_kernel exceeds 128 bytes and may cause high register 1351pressure. Consult with your hardware vendor to find the total register size 1352available and adjust the code, or use smaller sub-group size to avoid high 1353register pressure. 1354*/ 1355void block_topk_cluster_kernel ( const float * __restrict__ scores , 1356const int32_t * __restrict__ steps , 1357int64_t max_blocks , int64_t cap , 1358int32_t * __restrict__ ids , uint8_t * dpct_local ) { 1359#if STRATA_SEL_CLUSTER 1360auto item_ct1 = sycl::ext::oneapi::this_work_item:: get_nd_item < 3 > (); 1361auto keys = (uint32_t * ) dpct_local ; // this CTA's blocks' keys 1362auto & hin = 1363* sycl::ext::oneapi:: group_local_memory_for_overwrite < int[ 2 ][ CL_N ][ 256 ] > ( 1364sycl::ext::oneapi::this_work_item:: get_work_group < 13653 > ()); // the cluster's histograms, slot = the pushing rank 1366auto & hloc = 1367* sycl::ext::oneapi:: group_local_memory_for_overwrite < int[ 2 ][ 256 ] > ( 1368sycl::ext::oneapi::this_work_item:: get_work_group < 13693 > ()); // this CTA's histogram 1370auto & cnt = * sycl::ext::oneapi:: group_local_memory_for_overwrite < 1371unsigned long long[ CL_N ] > ( 1372sycl::ext::oneapi::this_work_item:: get_work_group < 13733 > ()); // per rank: its cells above thr (low 32 bits) and at it 1374// (high) 1375auto & s_warp = * sycl::ext::oneapi:: group_local_memory_for_overwrite < 1376unsigned long long[ 33 ] > ( 1377sycl::ext::oneapi::this_work_item:: get_work_group < 3 > ()); 1378auto & s_prefix = 1379* sycl::ext::oneapi:: group_local_memory_for_overwrite < uint32_t > ( 1380sycl::ext::oneapi::this_work_item:: get_work_group < 3 > ()); 1381auto & s_above = * sycl::ext::oneapi:: group_local_memory_for_overwrite < int > ( 1382sycl::ext::oneapi::this_work_item:: get_work_group < 3 > ()); 1383const unsigned rank = cl_rank (); 1384const int t = item_ct1 . get_local_id ( 2 ), lane = t & 31 , warp = t >> 5 ; 1385cl_arrive_relaxed (); // phase 0: this CTA runs 1386const int64_t qi = item_ct1 . get_group ( 1 ); 1387const int32_t * st = steps + qi * kStepCount ; 1388const int64_t n_kv = st [ kStepNKv ], n_bid = st [ kStepNBid ], width = st [ kStepWidth ]; 1389int32_t * out = ids + qi * cap ; 1390if ( n_kv <= width ) { // the identity, split over the cluster; no remote access 1391#pragma unroll 1392for (int64_t j = (int64_t) rank * CL_T + t ; j < n_kv ; 1393j += (int64_t) CL_N * CL_T ) out [ j ] = (int32_t) j ; 1394return ; 1395} 1396// the tail block n_bid weighs its cells (0..3); with none it is not a candidate (the reference skips w == 0) 1397const int wtail = (int) ( n_kv - n_bid * R ); 1398const int64_t nbe = n_bid + ( wtail > 0 ? 1 : 0 ); 1399const int64_t per = ( nbe + CL_N - 1 ) / CL_N ; // <= ceil(max_blocks / CL_N), the keys the host sized 1400const int64_t lo = (int64_t) rank * per < nbe ? (int64_t) rank * per : nbe ; 1401const int64_t hi = lo + per < nbe ? lo + per : nbe ; 1402const int n = (int) ( hi - lo ); 1403const int tail_i = ( wtail > 0 && n_bid >= lo && n_bid < hi ) ? (int) ( n_bid - lo ) : -1 ; 1404const float * sc = scores + qi * max_blocks + lo ; 1405#pragma unroll 1406for (int i = t ; i < n ; i += CL_T ) keys [ i ] = order_key ( sc [ i ]); 1407#pragma unroll 1408for (int i = t ; i < 2 * 256 ; i += CL_T )( & hloc [ 0 ][ 0 ])[ i ] = 0 ; 1409/* 1410DPCT1065: Consider replacing sycl::nd_item::barrier() with 1411sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better 1412performance if there is no access to global memory. 1413*/ 1414item_ct1 . barrier (); 1415uint32_t prefix = 0 ; 1416int above = 0 ; // cells strictly above the digits fixed so far 1417for (int pass = 0 ; pass < 4 ; ++ pass ) { 1418const int shift = 24 - 8 * pass ; 1419const uint32_t hmask = pass == 0 ? 0u : ( 0xffffffffu << ( shift + 8 )); 1420int * hl = hloc [ pass & 1 ]; 1421// warp-aggregated: the scores share their top bits, so plain atomics would queue on a few bins 1422for (int i0 = 0 ; i0 < n ; i0 += CL_T ) { 1423const int i = i0 + t ; 1424int bin = -1 ; 1425if ( i < n ) { 1426const uint32_t k = keys [ i ]; 1427if (( k & hmask ) == prefix ) bin = (int) (( k >> shift ) & 255 ); 1428} 1429const unsigned same = dpct:: match_any_over_sub_group ( 1430sycl::ext::oneapi::this_work_item:: get_sub_group (), 0xffffffffu , 1431bin ); 1432if ( bin >= 0 && lane == dpct:: ffs < int > ( same ) - 1 ) 1433dpct:: atomic_fetch_add < 1434sycl::access::address_space::generic_space > ( 1435& hl [ bin ], sycl:: popcount ( same ) * R ); 1436if ( bin >= 0 && i == tail_i ) dpct:: atomic_fetch_add < 1437sycl::access::address_space::generic_space > ( & hl [ bin ], 1438wtail - R ); 1439} 1440/* 1441DPCT1118: SYCL group functions and algorithms must be encountered in 1442converged control flow. You may need to adjust the code. 1443*/ 1444/* 1445DPCT1065: Consider replacing sycl::nd_item::barrier() with 1446sycl::nd_item::barrier(sycl::access::fence_space::local_space) for 1447better performance if there is no access to global memory. 1448*/ 1449item_ct1 . barrier (); 1450if ( pass == 0 ) cl_wait (); // phase 0 done: every CTA's shared memory is there 1451for (int i = t ; i < CL_N * 64 ; i += CL_T ) { // the histogram into slot `rank` of every CTA, as int4 1452const int dst = i >> 6 , c = i & 63 ; 1453* cl_map ( reinterpret_cast < sycl::int4 *> ( & hin [ pass & 1 ][ rank ][ 0 ]) + c , 1454(unsigned) dst ) = 1455reinterpret_cast < const sycl::int4 *> ( hl )[ c ]; 1456} 1457#pragma unroll 1458for (int i = t ; i < 256 ; i += CL_T ) hloc [( pass + 1 ) & 1 ][ i ] = 0 ; 1459cl_arrive (); 1460cl_wait (); 1461if ( warp == 0 ) { 1462// lane L owns digits 255 - 8L down to 248 - 8L; the digit holding the need-th cell from the top 1463const int need = (int) width - above ; 1464int tot [ 8 ], part = 0 ; 1465#pragma unroll 1466for (int k = 0 ; k < 8 ; ++ k ) { 1467const int d = 255 - 8 * lane - k ; 1468int v = 0 ; 1469#pragma unroll 1470for (int r = 0 ; r < CL_N ; ++ r ) v += hin [ pass & 1 ][ r ][ d ]; 1471tot [ k ] = v ; 1472part += v ; 1473} 1474int incl = part ; 1475#pragma unroll 1476for (int o = 1 ; o < 32 ; o <<= 1 ) { 1477/* 1478DPCT1108: '__shfl_up_sync' was migrated with the experimental 1479feature masked sub_group function which may not be supported by 1480all compilers or runtimes. You may need to adjust the code. 1481*/ 1482const int y = dpct::experimental:: shift_sub_group_right ( 14830xffffffffu , 1484sycl::ext::oneapi::this_work_item:: get_sub_group (), incl , 1485o ); 1486if ( lane >= o ) incl += y ; 1487} 1488const int excl = incl - part ; 1489const unsigned hit = sycl:: reduce_over_group ( 1490sycl::ext::oneapi::this_work_item:: get_sub_group (), 1491( 0xffffffffu & 1492( 0x1 << sycl::ext::oneapi::this_work_item:: get_sub_group () 1493. get_local_linear_id ())) && 1494excl < need && incl >= need 1495? ( 0x1 << sycl::ext::oneapi::this_work_item:: get_sub_group () 1496. get_local_linear_id ()) 1497: 0 , 1498sycl::ext::oneapi:: plus <> ()); 1499// no hit cannot happen (the cells total n_kv > width); the reference would then take digit 0 1500const int who = hit ? dpct:: ffs < int > ( hit ) - 1 : 31 ; 1501if ( lane == who ) { 1502int acc = excl , k = 0 ; 1503#pragma unroll 1504for (; k < 7 ; ++ k ) { 1505if ( acc + tot [ k ] >= need ) break ; 1506acc += tot [ k ]; 1507} 1508s_prefix = prefix | ((uint32_t) ( 255 - 8 * lane - k ) << shift ); 1509s_above = above + acc ; 1510} 1511} 1512/* 1513DPCT1118: SYCL group functions and algorithms must be encountered in 1514converged control flow. You may need to adjust the code. 1515*/ 1516/* 1517DPCT1065: Consider replacing sycl::nd_item::barrier() with 1518sycl::nd_item::barrier(sycl::access::fence_space::local_space) for 1519better performance if there is no access to global memory. 1520*/ 1521item_ct1 . barrier (); 1522prefix = s_prefix ; 1523above = s_above ; 1524} 1525const uint32_t thr = prefix ; 1526const int64_t eq_budget = width - above ; // cells at thr that fit, lowest index first 1527// each thread a contiguous run of the CTA's keys; an odd run length keeps the shared reads conflict-free 1528int seg = ( n + CL_T - 1 ) / CL_T ; 1529if (( seg & 1 ) == 0 && seg > 0 ) ++ seg ; 1530const int s0 = t * seg < n ? t * seg : n , s1 = s0 + seg < n ? s0 + seg : n ; 1531uint32_t gt = 0 , eq = 0 ; 1532for (int i = s0 ; i < s1 ; ++ i ) { 1533const uint32_t k = keys [ i ], w = i == tail_i ? (uint32_t) wtail : (uint32_t) R ; 1534if ( k > thr ) gt += w ; 1535else if ( k == thr ) eq += w ; 1536} 1537unsigned long long cta ; 1538const unsigned long long before = 1539cl_excl_scan64 ((unsigned long long) gt | ((unsigned long long) eq << 32 ), s_warp , cta ); 1540if ( t < CL_N ) * cl_map ( & cnt [ rank ], (unsigned) t ) = cta ; 1541cl_arrive (); 1542cl_wait (); 1543int64_t gt_off = 0 , eq_off = 0 ; 1544#pragma unroll 1545for (unsigned r = 0 ; r < rank ; ++ r ) { 1546gt_off += (int64_t) ( cnt [ r ] & 0xffffffffu ); 1547eq_off += (int64_t) ( cnt [ r ] >> 32 ); 1548} 1549const int64_t eq_before = eq_off + (int64_t) ( before >> 32 ); 1550int64_t wpos = gt_off + (int64_t) ( before & 0xffffffffu ) + ( eq_before < eq_budget ? eq_before : eq_budget ); 1551int64_t eq_left = eq_budget - eq_before ; 1552if ( eq_left < 0 ) eq_left = 0 ; 1553for (int i = s0 ; i < s1 ; ++ i ) { 1554const uint32_t k = keys [ i ]; 1555const int w = i == tail_i ? wtail : R ; 1556const int64_t b = lo + i ; 1557if ( k > thr ) { 1558#pragma unroll 1559for (int c = 0 ; c < w ; ++ c ) out [ wpos ++ ] = (int32_t)( b * R + c ); 1560} else if ( k == thr ) { 1561#pragma unroll 1562for (int c = 0 ; c < w && eq_left > 0 ; ++ c , -- eq_left ) 1563out [ wpos ++ ] = (int32_t)( b * R + c ); 1564} 1565} 1566#else 1567(void) scores ; (void) steps ; (void) max_blocks ; (void) cap ; (void) ids ; 1568/* unreachable on SYCL: the launcher refuses this device */ 1569#endif 1570} 1571#endif // !__HIPCC__ 1572} // namespace 1573 1574void qsa_block_scores_rows ( const QsaScoreRows & rows , const float * q_idx , const int32_t * steps , int64_t nq , 1575int64_t max_blocks , const QsaShapes & s , float * scores , void * stream ) { 1576if ( nq <= 0 ) return ; 1577if ( s . idx_dim != IDX_DIM || s . idx_n_head != IDX_HEADS || s . idx_block != R || nq > MQ || rows . n != nq ) { 1578std:: fprintf ( stderr , "qsa_block_scores_rows: unsupported geometry\n" ); 1579std:: exit ( 1 ); 1580} 1581static const bool early = [] { const char * v = std:: getenv ( "STRATA_QSA_EARLY_EXIT" ); return v == nullptr || std:: atoi ( v ) != 0 ; }(); 1582const QsaScoreRows srow = rows ; 1583auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental:: use_root_sync }; 1584strata::kprof:: kp (strata:: q_of ( stream ), __FILE__ , __func__ , __LINE__ ) -> submit ([ & ](sycl::handler & cgh ) { 1585auto early_ct7 = early ; 1586cgh . parallel_for < dpct_kernel_name < class block_scores_rows_kernel_a3 >> ( 1587sycl:: nd_range < 3 > (sycl:: range ( 1 , 1 , 256 ) * sycl:: range ( 1 , 1 , SCORE_WARPS * 32 ), 1588sycl:: range ( 1 , 1 , SCORE_WARPS * 32 )), 1589exp_props , [ = ](sycl::nd_item < 3 > item_ct1 ) [[ sycl :: reqd_sub_group_size ( 32 )]] { 1590block_scores_multi_kernel ( nullptr , nullptr , q_idx , steps , (int) nq , max_blocks , scores , early_ct7 , srow ); 1591}); 1592}); 1593} 1594 1595// SYCL port: the prompt path's block scores as oneMKL GEMM tiles (prefill.cpp): S[q * IDX_HEADS + h][b - b0] is 1596// pooled[b] . q_idx[q][h] for the blocks [b0, b0 + nb); this turns them into scores[q][b] - relu per indexer head, 1597// summed in head order - and gives block n_bid the dead key with block_scores_kernel's +1e9 rule. Blocks past a 1598// query's n_bid are not written, as in qsa_block_scores. FP32, another summation order than the warp kernel: not 1599// bitwise (relative error 2-4e-7; the same selection but for near-ties). 1600void qsa_block_scores_reduce ( const float * S , int64_t ld , int64_t b0 , int64_t nb , const float * dead , const float * q_idx , 1601const int32_t * steps , int64_t nq , int64_t max_blocks , float * scores , void * stream ) { 1602if ( nq <= 0 || nb <= 0 ) return ; 1603strata:: q_of ( stream ) -> parallel_for (sycl:: range < 2 > ((size_t) nq , (size_t) nb ), [ = ](sycl::id < 2 > it ) { 1604const int64_t qi = (int64_t) it [ 0 ], b = b0 + (int64_t) it [ 1 ]; 1605const int64_t n_kv = steps [ qi * kStepCount + kStepNKv ], n_bid = steps [ qi * kStepCount + kStepNBid ]; 1606if ( b > n_bid || b >= max_blocks ) return ; 1607float score = 0.0f ; 1608if ( b == n_bid ) { 1609for (int h = 0 ; h < IDX_HEADS ; ++ h ) { 1610float d = 0.0f ; 1611for (int i = 0 ; i < IDX_DIM ; ++ i ) d += dead [ i ] * q_idx [( qi * IDX_HEADS + h ) * IDX_DIM + i ]; 1612score += d > 0.0f ? d : 0.0f ; 1613} 1614if ( n_kv % R != 0 ) score += 1e9f ; 1615} else { 1616for (int h = 0 ; h < IDX_HEADS ; ++ h ) { 1617const float d = S [(size_t) ( qi * IDX_HEADS + h ) * (size_t) ld + (size_t) ( b - b0 )]; 1618score += d > 0.0f ? d : 0.0f ; 1619} 1620} 1621scores [(size_t) qi * (size_t) max_blocks + (size_t) b ] = score ; 1622}); 1623} 1624 1625void qsa_block_scores ( const float * pooled , const float * dead , const float * q_idx , const int32_t * steps , int64_t nq , 1626int64_t max_blocks , const QsaShapes & s , float * scores , void * stream , int64_t active_blocks ) { 1627if ( nq <= 0 ) return ; 1628if ( s . idx_dim != IDX_DIM || s . idx_n_head != IDX_HEADS || s . idx_block != R || nq > 65535 ) { 1629std:: fprintf ( stderr , "qsa_block_scores: unsupported indexer geometry\n" ); 1630std:: exit ( 1 ); 1631} 1632// a block past a query's n_bid returns at once: the grid need only reach the batch's largest n_bid (C-1) 1633static const bool multi = [] { const char * v = std:: getenv ( "STRATA_SCORES_MULTI" ); return v == nullptr || std:: atoi ( v ) != 0 ; }(); 1634if ( multi && nq <= MQ && active_blocks <= 0 ) { // no active count: decode (captured or not) and prefill's pooled16 1635// STRATA_QSA_EARLY_EXIT=0 keeps the old staging (every CTA loads the queries first); the scores are the same bits 1636static const bool early = [] { const char * v = std:: getenv ( "STRATA_QSA_EARLY_EXIT" ); return v == nullptr || std:: atoi ( v ) != 0 ; }(); 1637{ 1638auto exp_props = sycl::ext::oneapi::experimental::properties{ 1639sycl::ext::oneapi::experimental:: use_root_sync }; 1640 1641strata::kprof:: kp (strata:: q_of ( stream ), __FILE__ , __func__ , __LINE__ ) 1642-> submit ([ & ](sycl::handler & cgh ) { 1643auto early_ct7 = early ; 1644 1645cgh . parallel_for < dpct_kernel_name < 1646class block_scores_multi_kernel_dea7d4 >> ( 1647sycl:: nd_range < 3 > ( 1648sycl:: range ( 1 , 1 , 256 ) * 1649sycl:: range ( 1 , 1 , SCORE_WARPS * 32 ), 1650sycl:: range ( 1 , 1 , SCORE_WARPS * 32 )), 1651exp_props , 1652[ = ](sycl::nd_item < 3 > item_ct1 ) 1653[[ sycl :: reqd_sub_group_size ( 32 )]] { 1654block_scores_multi_kernel ( 1655pooled , dead , q_idx , steps , (int) nq , 1656max_blocks , scores , early_ct7 ); 1657}); 1658}); 1659} 1660/* 1661DPCT1010: SYCL uses exceptions to report errors and does not use 1662the error codes. The cudaGetLastError function call was replaced with 0. 1663You need to rewrite this code. 1664*/ 1665const dpct::err0 e = 0 ; 1666/* 1667DPCT1009: SYCL reports errors using exceptions and does not use 1668error codes. Please replace the "get_error_string_dummy(...)" with a 1669real error-handling function. 1670*/ 1671 1672return ; 1673} 1674const int64_t reach = active_blocks > 0 && active_blocks < max_blocks ? active_blocks : max_blocks ; 1675const dpct::dim3 grid ((unsigned)(( reach + SCORE_WARPS - 1 ) / SCORE_WARPS ), 1676(unsigned) nq ); 1677{ 1678auto exp_props = sycl::ext::oneapi::experimental::properties{ 1679sycl::ext::oneapi::experimental:: use_root_sync }; 1680 1681strata::kprof:: kp (strata:: q_of ( stream ), __FILE__ , __func__ , __LINE__ ) 1682-> template parallel_for < dpct_kernel_name < class block_scores_kernel_925c9d >> ( 1683sycl:: nd_range < 3 > ( grid * sycl:: range ( 1 , 1 , SCORE_WARPS * 32 ), 1684sycl:: range ( 1 , 1 , SCORE_WARPS * 32 )), 1685exp_props , 1686[ = ](sycl::nd_item < 3 > item_ct1 ) 1687[[ sycl :: reqd_sub_group_size ( 32 )]] { 1688block_scores_kernel ( pooled , dead , q_idx , steps , 1689max_blocks , scores ); 1690}); 1691} 1692/* 1693DPCT1010: SYCL uses exceptions to report errors and does not use the 1694error codes. The cudaGetLastError function call was replaced with 0. You 1695need to rewrite this code. 1696*/ 1697const dpct::err0 e = 0 ; 1698/* 1699DPCT1009: SYCL reports errors using exceptions and does not use error 1700codes. Please replace the "get_error_string_dummy(...)" with a real 1701error-handling function. 1702*/ 1703} 1704 1705bool qsa_block_scores_tc ( const float * pooled , const float * dead , 1706const float * q_idx , const int32_t * steps , int64_t nq , 1707int64_t max_blocks , const QsaShapes & s , float * scores , 1708void * stream , int64_t active_blocks ) try { 1709if ( nq <= 0 ) return true; 1710if ( s . idx_dim != IDX_DIM || s . idx_n_head != IDX_HEADS || s . idx_block != R || nq > 65535 * TC_QT ) return false; 1711#if defined( __HIPCC__ ) 1712// AMD: the gfx12 (RDNA4) WMMA scorer, opt-in (STRATA_SELECT_WMMA=1): it selects slightly differently from the warp 1713// kernel (254/256 queries the same), so the default keeps the warp kernel; every other target keeps it too (false) 1714static const bool wmma_on = [] { 1715const char * v = std:: getenv ( "STRATA_SELECT_WMMA" ); 1716return v != nullptr && v [ 0 ] != '\0' && v [ 0 ] != '0' ; 1717}(); 1718if (! wmma_on || ! sel_gfx12_device ()) return false; 1719{ 1720const int64_t reach = active_blocks > 0 && active_blocks < max_blocks ? active_blocks : max_blocks ; 1721const int64_t per = (int64_t) 4 * WITER * 16 ; 1722const dim3 grid ((unsigned) (( reach + per - 1 ) / per ), (unsigned) (( nq + WQT - 1 ) / WQT )); 1723block_scores_wmma_kernel << < grid , 128 , 0 , ( cudaStream_t ) stream > >>( pooled , q_idx , steps , nq , max_blocks , reach , scores ); 1724block_scores_tail_kernel <<<( unsigned ) nq , 32 , 0 , ( cudaStream_t ) stream > >>( dead , q_idx , steps , max_blocks , scores ); 1725const cudaError_t e = cudaGetLastError(); 1726if ( e != cudaSuccess ) { std::fprintf( stderr , "qsa_block_scores_tc: %s\n" , cudaGetErrorString( e )); std::exit( 1 ); } 1727return true; 1728} 1729#else 1730{ // sm_80 or newer (TF32 MMA); an older card keeps the warp kernel 1731static int cc_major [ 64 ] = {}; 1732int dev = 0 ; 1733/* 1734DPCT1026: The call to cudaGetLastError was removed because this 1735functionality is redundant in SYCL. 1736*/ 1737if (DPCT_CHECK_ERROR( dev = dpct::get_current_device_id()) != 0 || 1738dev < 0 || dev >= 64 ) { 1739; return false; 1740} 1741if ( cc_major [ dev ] == 0 ) { 1742int major = 0 ; 1743if (DPCT_CHECK_ERROR( 1744major = dpct::get_device( dev ).get_major_version()) != 0 ) { 1745/* 1746DPCT1026: The call to cudaGetLastError was removed because 1747this functionality is redundant in SYCL. 1748*/ 1749return false; 1750} 1751// STRATA_QSA_WARP=1|select (an A/B arm): the pre-sm_80 kernels on any card, as RTX 20 runs them 1752const char * w = std::getenv( "STRATA_QSA_WARP" ); 1753cc_major [ dev ] = w && (!std::strcmp( w , "1" ) || !std::strcmp( w , "select" )) ? 7 : strata::cc_major_of( major ); 1754} 1755( void ) cc_major [ dev ]; 1756return false; // SYCL: the tensor-core kernel is not ported yet; the caller takes the older kernel 1757} 1758static bool attr [ 64 ] = {}; // the shared-memory opt-in is per device (a layer split runs it on several) 1759int adev = 0 ; 1760adev = dpct::get_current_device_id(); 1761/* 1762DPCT1083: The size of local memory in the migrated code may be different 1763from the original code. Check that the allocated memory size in the migrated 1764code is correct. 1765*/ 1766const int bytes = ( TC_QT * TC_QS + TC_NB * TC_KS ) * ( int ) sizeof ( float ); 1767if (! attr [ adev ]) { 1768/* 1769DPCT1027: The call to cudaFuncSetAttribute was replaced with 0 1770because SYCL currently does not support corresponding setting. 1771*/ 1772if ( 0 != 0 ) { 1773/* 1774DPCT1026: The call to cudaGetLastError was removed because this 1775functionality is redundant in SYCL. 1776*/ 1777return false; 1778} 1779attr [ adev ] = true; 1780} 1781const int64_t reach = active_blocks > 0 && active_blocks < max_blocks ? active_blocks : max_blocks ; 1782const int64_t per = ( int64_t ) TC_NB * TC_ITER ; 1783const dpct:: dim3 grid (( unsigned )(( reach + per - 1 ) / per ), 1784( unsigned )(( nq + TC_QT - 1 ) / TC_QT )); 1785{ 1786auto exp_props = sycl::ext::oneapi::experimental:: properties { 1787sycl::ext::oneapi::experimental:: use_root_sync }; 1788 1789strata::kprof:: kp (strata::q_of( stream ), __FILE__ , __func__ , __LINE__ ) 1790-> submit([ & ](sycl:: handler & cgh ) { 1791sycl:: local_accessor < uint8_t , 1 > dpct_local_acc_ct1 ( 1792sycl::range( bytes ), cgh ); 1793 1794cgh .parallel_for < 1795dpct_kernel_name < class block_scores_tc_kernel_bc5f07 >> ( 1796sycl::nd_range < 3 > ( grid * sycl::range( 1 , 1 , 128 ), 1797sycl::range( 1 , 1 , 128 )), 1798exp_props , [ = ](sycl:: nd_item < 3 > item_ct1 ) { 1799block_scores_tc_kernel( 1800pooled , q_idx , steps , nq , max_blocks , reach , scores , 1801dpct_local_acc_ct1 1802.get_multi_ptr < sycl::access::decorated:: no > () 1803.get()); 1804}); 1805}); 1806} 1807{ 1808auto exp_props = sycl::ext::oneapi::experimental:: properties { 1809sycl::ext::oneapi::experimental:: use_root_sync }; 1810 1811strata::kprof:: kp (strata::q_of( stream ), __FILE__ , __func__ , __LINE__ ) 1812-> template parallel_for < 1813dpct_kernel_name < class block_scores_tail_kernel_70dfaa >> ( 1814sycl::nd_range < 3 > (sycl::range( 1 , 1 , ( unsigned ) nq ) * 1815sycl::range( 1 , 1 , 32 ), 1816sycl::range( 1 , 1 , 32 )), 1817exp_props , 1818[ = ](sycl:: nd_item < 3 > item_ct1 ) 1819[[ sycl :: reqd_sub_group_size ( 32 )]] { 1820block_scores_tail_kernel( dead , q_idx , steps , max_blocks , 1821scores ); 1822}); 1823} 1824/* 1825DPCT1010: SYCL uses exceptions to report errors and does not use the 1826error codes. The cudaGetLastError function call was replaced with 0. You 1827need to rewrite this code. 1828*/ 1829const dpct:: err0 e = 0 ; 1830/* 1831DPCT1009: SYCL reports errors using exceptions and does not use error 1832codes. Please replace the "get_error_string_dummy(...)" with a real 1833error-handling function. 1834*/ 1835 1836return true; 1837#endif 1838} 1839catch (sycl:: exception const & exc ) { 1840std:: cerr << exc .what() << "Exception caught at file:" << __FILE__ 1841<< ", line:" << __LINE__ << std:: endl ; 1842std::exit( 1 ); 1843} 1844 1845void qsa_block_topk_ref( const float * scores , const int32_t * steps , int64_t nq , int64_t max_blocks , int64_t cap , 1846const QsaShapes & s , int32_t * ids , void * stream ) { 1847if ( nq <= 0 ) return ; 1848if ( s . idx_block != R || cap < qsa_selection_width( kTopkMaxCells , s )) { 1849std::fprintf( stderr , "qsa_block_topk: unsupported geometry or cap\n" ); 1850std::exit( 1 ); 1851} 1852{ 1853auto exp_props = sycl::ext::oneapi::experimental:: properties { 1854sycl::ext::oneapi::experimental:: use_root_sync }; 1855 1856strata::kprof:: kp (strata::q_of( stream ), __FILE__ , __func__ , __LINE__ ) 1857-> template parallel_for < dpct_kernel_name < class block_topk_kernel_213104 >> ( 1858sycl::nd_range < 3 > (sycl::range( 1 , 1 , ( unsigned ) nq ) * 1859sycl::range( 1 , 1 , TOPK_T ), 1860sycl::range( 1 , 1 , TOPK_T )), 1861exp_props , [ = ](sycl:: nd_item < 3 > item_ct1 ) { 1862block_topk_kernel( scores , steps , max_blocks , cap , ids ); 1863}); 1864} 1865/* 1866DPCT1010: SYCL uses exceptions to report errors and does not use the 1867error codes. The cudaGetLastError function call was replaced with 0. You 1868need to rewrite this code. 1869*/ 1870const dpct:: err0 e = 0 ; 1871/* 1872DPCT1009: SYCL reports errors using exceptions and does not use error 1873codes. Please replace the "get_error_string_dummy(...)" with a real 1874error-handling function. 1875*/ 1876} 1877 1878#if !defined( __HIPCC__ ) 1879// Only Turing has a retained model measurement for this CUDA dispatch. Other CUDA devices keep the capacity rule 1880// (the RTX 5070 regression below). Cache the properties per calling thread; layer-split device switches are checked. 1881static bool topk_active_turing_device() try { 1882int dev = 0 ; 1883if (DPCT_CHECK_ERROR( dev = dpct::get_current_device_id()) != 18840 ) return false; 1885static thread_local int cached_device = -1 ; 1886static thread_local bool turing = false; 1887if ( dev != cached_device ) { 1888dpct:: device_info prop {}; 1889if (DPCT_CHECK_ERROR(dpct::get_device( dev ).get_device_info( prop )) != 18900 ) return false; 1891/* 1892DPCT1005: The SYCL device version is different from CUDA Compute 1893Compatibility. You may need to rewrite this code. 1894*/ 1895turing = prop .get_major_version() == 7 && prop .get_minor_version() == 5 ; 1896cached_device = dev ; 1897} 1898return turing ; 1899} 1900catch (sycl:: exception const & exc ) { 1901std:: cerr << exc .what() << "Exception caught at file:" << __FILE__ 1902<< ", line:" << __LINE__ << std:: endl ; 1903std::exit( 1 ); 1904} 1905#endif 1906 1907bool qsa_block_topk_cluster( const float * scores , const int32_t * steps , 1908int64_t nq , int64_t max_blocks , int64_t cap , 1909const QsaShapes & s , int32_t * ids , 1910void * stream ) try { 1911#if 1 // SYCL port: no thread-block clusters (sm_90): the caller takes the plain top-k 1912( void ) scores ; ( void ) steps ; ( void ) nq ; ( void ) max_blocks ; ( void ) cap ; ( void ) s ; ( void ) ids ; ( void ) stream ; 1913return false; 1914#else 1915if ( nq <= 0 ) return true; 1916if ( s . idx_block != R || cap < qsa_selection_width( kTopkMaxCells , s ) || nq > 65535 || max_blocks <= 0 ) return false; 1917const size_t smem = ( size_t ) (( max_blocks + CL_N - 1 ) / CL_N ) * sizeof ( uint32_t ); 1918// Per device (a layer split runs on several): 1 the cluster kernel runs here, 2 it does not. It needs sm_90+ (the 1919// card's, or STRATA_EMULATE_CC's) AND code built for it: a build with only older code JIT-compiles their PTX, whose 1920// copy of this kernel is a trap - the function's PTX version says which. `opt`: the dynamic shared memory opted in. 1921static int ok [ 64 ] = {}; 1922static size_t opt [ 64 ] = {}; 1923int dev = 0 ; 1924/* 1925DPCT1026: The call to cudaGetLastError was removed because this 1926functionality is redundant in SYCL. 1927*/ 1928if (DPCT_CHECK_ERROR( dev = dpct::get_current_device_id()) != 0 || dev < 0 || 1929dev >= 64 ) { 1930; return false; 1931} 1932if ( ok [ dev ] == 0 ) { 1933int major = 0 ; 1934dpct:: kernel_function_info fa {}; 1935const bool code = 1936DPCT_CHECK_ERROR( 1937major = dpct::get_device( dev ).get_major_version()) == 0 && 1938strata::cc_major_of( major ) >= 9 && 1939DPCT_CHECK_ERROR(dpct::get_kernel_function_info( 1940& fa , ( const void * ) block_topk_cluster_kernel )) == 0 && 1941fa . ptxVersion >= 90 && fa . binaryVersion >= 90 ; 1942/* 1943DPCT1026: The call to cudaGetLastError was removed because this 1944functionality is redundant in SYCL. 1945*/ 1946ok [ dev ] = code ? 1 : 2 ; 1947} 1948if ( ok [ dev ] != 1 ) return false; 1949if ( smem > opt [ dev ]) { // a larger capacity: opt in, and check that a cluster of CL_N such CTAs can be resident 1950int clusters = 0 ; 1951cudaLaunchConfig_t q {}; 1952cudaLaunchAttribute qa [ 1 ]; 1953qa [ 0 ]. id = cudaLaunchAttributeClusterDimension ; 1954qa [ 0 ]. val . clusterDim . x = CL_N ; 1955qa [ 0 ]. val . clusterDim . y = 1 ; 1956qa [ 0 ]. val . clusterDim . z = 1 ; 1957q . gridDim = dpct::dim3( CL_N , 1 , 1 ); 1958q . blockDim = dpct::dim3( CL_T , 1 , 1 ); 1959q . dynamicSmemBytes = smem ; 1960q . attrs = qa ; 1961q . numAttrs = 1 ; 1962/* 1963DPCT1027: The call to cudaFuncSetAttribute was replaced with 0 1964because SYCL currently does not support corresponding setting. 1965*/ 1966if ( 0 != 0 || 1967/* 1968DPCT1007: Migration of cudaOccupancyMaxActiveClusters is not 1969supported. 1970*/ 1971cudaOccupancyMaxActiveClusters( & clusters , block_topk_cluster_kernel , 1972& q ) != 0 || 1973clusters < 1 ) { 1974/* 1975DPCT1026: The call to cudaGetLastError was removed because this 1976functionality is redundant in SYCL. 1977*/ 1978return false; // this capacity takes the one-CTA kernels; a smaller 1979// one may still fit 1980} 1981opt [ dev ] = smem ; 1982} 1983cudaLaunchConfig_t cfg {}; 1984cudaLaunchAttribute at [ 1 ]; 1985at [ 0 ]. id = cudaLaunchAttributeClusterDimension ; 1986at [ 0 ]. val . clusterDim . x = CL_N ; 1987at [ 0 ]. val . clusterDim . y = 1 ; 1988at [ 0 ]. val . clusterDim . z = 1 ; 1989cfg . gridDim = dpct::dim3( CL_N , ( unsigned ) nq , 1 ); 1990cfg . blockDim = dpct::dim3( CL_T , 1 , 1 ); 1991cfg . dynamicSmemBytes = smem ; 1992cfg . stream = strata::q_of( stream ); 1993cfg . attrs = at ; 1994cfg . numAttrs = 1 ; 1995const dpct:: err0 e = cudaLaunchKernelEx( 1996& cfg , block_topk_cluster_kernel , scores , steps , max_blocks , cap , ids ); 1997/* 1998DPCT1009: SYCL reports errors using exceptions and does not use error 1999codes. Please replace the "get_error_string_dummy(...)" with a real 2000error-handling function. 2001*/ 2002 2003return true; 2004#endif 2005} 2006catch (sycl:: exception const & exc ) { 2007std:: cerr << exc .what() << "Exception caught at file:" << __FILE__ 2008<< ", line:" << __LINE__ << std:: endl ; 2009std::exit( 1 ); 2010} 2011 2012void qsa_block_topk( const float * scores , const int32_t * steps , int64_t nq , int64_t max_blocks , int64_t cap , 2013const QsaShapes & s , int32_t * ids , void * stream , int64_t active_blocks ) { 2014// keys in registers when every query's blocks fit (contexts up to ~135K cells), else (CUDA) the same threads 2015// reading them from memory; the same ids. STRATA_TOPK_OLD=1: the original kernel 2016static const bool old = std::getenv( "STRATA_TOPK_OLD" ) != nullptr ; 2017if ( nq <= 0 ) return ; 2018#if !defined( __HIPCC__ ) 2019// sm_90+: a cluster of CL_N CTAs per query for the calls of a few queries (decode windows); the same ids. 2020// STRATA_QSA_CLUSTER=0: the one-CTA kernels below 2021static const bool cluster = [] { 2022const char * v = std::getenv( "STRATA_QSA_CLUSTER" ); 2023return ! v || std::atoi( v ) != 0 ; 2024}(); 2025if ( cluster && ! old && nq <= CL_MAXQ && qsa_block_topk_cluster( scores , steps , nq , max_blocks , cap , s , ids , stream )) 2026return ; 2027#endif 2028// the blocks a query can have: the call's active count when the caller knows it (the prompt path), else the capacity. 2029// Decode (no count) keeps the capacity rule and the original register width: nothing changes there. 2030#if defined( __HIPCC__ ) 2031const bool counted = active_blocks > 0 ; 2032#else 2033// Turing: --max-context 262144 makes the stride 65538, even while a 131K prompt's active blocks fit in 2034// TK_T * TK_PER registers. Use the prefill bound on sm_75, keeping max_blocks as the score-row stride. 2035// Other CUDA devices keep 0.1.32's capacity rule: #337 was measured on RDNA4, and RTX 5070 64K prompts were 2036// 1-3% slower. Decode/captured graphs omit the bound and never query the device here. 2037static const bool capacity_guard = std::getenv( "STRATA_TOPK_CAPACITY_GUARD" ) != nullptr ; 2038// STRATA_TOPK_ACTIVE_ANY=1 (tests): the Turing dispatch on any CUDA card, so qsa_topk_active_parity checks it 2039// on whatever card runs the tests (the kernels are the same on every architecture) 2040static const bool any_card = [] { const char * v = std::getenv( "STRATA_TOPK_ACTIVE_ANY" ); return v && v [ 0 ] == '1' ; }(); 2041const bool counted = ! capacity_guard && active_blocks > 0 && active_blocks <= max_blocks && 2042( any_card || topk_active_turing_device()); 2043#endif 2044const int64_t reach = counted && active_blocks < max_blocks ? active_blocks : max_blocks ; 2045const int64_t fit = ( int64_t ) TK_T * ( counted ? TK_PER_MAX : TK_PER ); 2046#if defined( __HIPCC__ ) 2047constexpr int64_t kRegMinBlocks = 7168 ; // gfx1201: below ~28K cells the 1,024-thread kernel's fixed cost loses to the ref 2048const bool too_small = counted && reach < kRegMinBlocks ; 2049if ( old || too_small || reach > fit ) { 2050#else 2051constexpr int64_t kWideMinBlocks = 4608 ; // RTX 3060: a prompt batch below ~18K cells is faster on the ref 2052const bool too_small = reach > fit && active_blocks > 0 && active_blocks < kWideMinBlocks ; 2053if ( old || too_small ) { 2054#endif 2055qsa_block_topk_ref( scores , steps , nq , max_blocks , cap , s , ids , stream ); 2056return ; 2057} 2058if ( s . idx_block != R || cap < qsa_selection_width( kTopkMaxCells , s )) { 2059std::fprintf( stderr , "qsa_block_topk: unsupported geometry or cap\n" ); 2060std::exit( 1 ); 2061} 2062#if !defined( __HIPCC__ ) 2063// Turing prefill (the `counted` bound) above ~90K cells (22,528 blocks): the wide kernel, which reads the keys 2064// coalesced, instead of the register kernel's uncoalesced per-thread runs (PR #743: 131K, 1.03 -> 0.75 ms); the 2065// same ids. STRATA_TOPK_STREAM=0 restores the register kernel there. 2066static const bool turing_wide = [] { 2067const char * v = std::getenv( "STRATA_TOPK_STREAM" ); 2068return v == nullptr || v [ 0 ] != '0' ; 2069}(); 2070if ( reach > fit || ( turing_wide && counted && reach > 22528 )) // past the register kernel's reach, or Turing's band 2071/* 2072DPCT1049: The work-group size passed to the SYCL kernel may exceed 2073the limit. To get the device limit, query 2074info::device::max_work_group_size. Adjust the work-group size if needed. 2075*/ 2076{ 2077auto exp_props = sycl::ext::oneapi::experimental:: properties { 2078sycl::ext::oneapi::experimental:: use_root_sync }; 2079 2080strata::kprof:: kp (strata::q_of( stream ), __FILE__ , __func__ , __LINE__ ) 2081-> template parallel_for < 2082dpct_kernel_name < class block_topk_wide_kernel_5162c4 >> ( 2083sycl::nd_range < 3 > (sycl::range( 1 , 1 , ( unsigned ) nq ) * 2084sycl::range( 1 , 1 , TK_T ), 2085sycl::range( 1 , 1 , TK_T )), 2086exp_props , 2087[ = ](sycl:: nd_item < 3 > item_ct1 ) 2088[[ sycl :: reqd_sub_group_size ( 32 )]] { 2089block_topk_wide_kernel( scores , steps , max_blocks , cap , 2090ids ); 2091}); 2092} else 2093#endif 2094if ( reach <= ( int64_t ) TK_T * TK_PER ) 2095/* 2096DPCT1049: The work-group size passed to the SYCL kernel may exceed 2097the limit. To get the device limit, query 2098info::device::max_work_group_size. Adjust the work-group size if needed. 2099*/ 2100{ 2101auto exp_props = sycl::ext::oneapi::experimental:: properties { 2102sycl::ext::oneapi::experimental:: use_root_sync }; 2103 2104strata::kprof:: kp (strata::q_of( stream ), __FILE__ , __func__ , __LINE__ ) 2105-> template parallel_for < dpct_kernel_name < class block_topk_reg_kernel_6ae5f0 , 2106dpct_kernel_scalar < TK_PER >>> ( 2107sycl::nd_range < 3 > (sycl::range( 1 , 1 , ( unsigned ) nq ) * 2108sycl::range( 1 , 1 , TK_T ), 2109sycl::range( 1 , 1 , TK_T )), 2110exp_props , 2111[ = ](sycl:: nd_item < 3 > item_ct1 ) 2112[[ sycl :: reqd_sub_group_size ( 32 )]] { 2113block_topk_reg_kernel < TK_PER > ( scores , steps , max_blocks , 2114cap , ids ); 2115}); 2116} else 2117/* 2118DPCT1049: The work-group size passed to the SYCL kernel may exceed 2119the limit. To get the device limit, query 2120info::device::max_work_group_size. Adjust the work-group size if needed. 2121*/ 2122{ 2123auto exp_props = sycl::ext::oneapi::experimental:: properties { 2124sycl::ext::oneapi::experimental:: use_root_sync }; 2125 2126strata::kprof:: kp (strata::q_of( stream ), __FILE__ , __func__ , __LINE__ ) 2127-> template parallel_for < dpct_kernel_name < class block_topk_reg_kernel_10a848 , 2128dpct_kernel_scalar < TK_PER_MAX >>> ( 2129sycl::nd_range < 3 > (sycl::range( 1 , 1 , ( unsigned ) nq ) * 2130sycl::range( 1 , 1 , TK_T ), 2131sycl::range( 1 , 1 , TK_T )), 2132exp_props , 2133[ = ](sycl:: nd_item < 3 > item_ct1 ) 2134[[ sycl :: reqd_sub_group_size ( 32 )]] { 2135block_topk_reg_kernel < TK_PER_MAX > ( scores , steps , 2136max_blocks , cap , ids ); 2137}); 2138} 2139/* 2140DPCT1010: SYCL uses exceptions to report errors and does not use the 2141error codes. The cudaGetLastError function call was replaced with 0. You 2142need to rewrite this code. 2143*/ 2144const dpct:: err0 e = 0 ; 2145/* 2146DPCT1009: SYCL reports errors using exceptions and does not use error 2147codes. Please replace the "get_error_string_dummy(...)" with a real 2148error-handling function. 2149*/ 2150} 2151 2152} // namespace strata::kernels