okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
db137d917
main
1// src/kernels/cuda/qsa_prompt_attn.cu - see include/strata/kernels/qsa_prompt_attn.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_prompt_attn.hpp" 12#include "strata/kernels/qsa_prompt_attn_xmx.hpp" 13#include "strata/kernels/qsa_prompt_attn_esimd.hpp" 14#include "strata/kernels/gfx_arch.hpp" 15#include "strata/kernels/kv_q8.hpp" 16#include "strata/kernels/kv_q4.hpp" 17 18#include <cmath> 19 20#include <cstdio> 21#include <cstdlib> 22#include <cstring> 23#include <type_traits> 24 25namespace strata::kernels { 26namespace { 27 28constexpr int HD = 256 ;// head_dim 29constexpr int G = strata::core::kCompiledGeometry .n_head / strata::core::kCompiledGeometry .n_head_kv ;// query heads per KV head (12 for Flash-Next); the tiles pad the rows to 16, so G <= 16 30static_assert(G >=1 && G <=16 ,"qsa_prompt_attn: query heads per KV head must be 1..16 (one M16 tile)" ); 31static_assert(HD == strata::core::kCompiledGeometry .head_dim && G == strata::core::kCompiledGeometry .n_head / strata::core::kCompiledGeometry .n_head_kv ,"qsa_prompt_attn is compiled for core/geometry.hpp" ); 32#ifndef D1_CH 33#define D1_CH 32 34#endif 35constexpr int CH = D1_CH ;// cells per chunk 36constexpr int THREADS = 128 ;// 4 warps: scores by cell (8 each), p.v by dimension (64 each = one int8 scale group) 37constexpr int QS = HD + 8 ;// q row stride in halves (bank-conflict-free fragment loads) 38 39// The MMA below needs sm_75 or newer (Turing runs it as two k=8 steps); cp.async needs sm_80. Builds for pre-sm_75 40// cards compile the MMA to a trap; qsa_prompt_attn_batch refuses such a device at run time, so the old kernel runs 41// there. Turing compiles cp_async16 to a trap as well and takes the v1 kernel instead of launch_i8. 42#if defined(__HIPCC__ )// AMD: no mma.sync / cp.async; the host keeps the old kernel (below) 43#define STRATA_PA_SM80 0 44#elif 0 // SYCL: inline PTX (mma/ldmatrix/cp.async) - the XMX port is pending; see tools/fixups.py 45#define STRATA_PA_SM80 1 46#else 47#define STRATA_PA_SM80 0 48#endif 49 50// m16n8k16 with f16 inputs needs sm_80. Turing (sm_75) has m16n8k8 with the SAME A/B/C register mapping, so the 51// k=16 step is two k=8 steps on the fragments as they are already laid out: a[0]/a[1] are rows gid/gid+8 at k columns 52// 2*tig..2*tig+1 (b[0]'s k rows), a[2]/a[3] the same rows at k columns 2*tig+8..2*tig+9 (b[1]'s k rows). The 53// products then add into the same FP32 C registers in the order hi-part-0, hi-part-1, which is the order the k16 54// instruction accumulates in as well - but the sum now rounds twice, so the two paths do not agree bit for bit. 55__dpct_inline__ void mma16816 (float * c ,const uint32_t * a ,const uint32_t * b ) { 56#if !STRATA_PA_SM80 && \ 57 (defined(__HIPCC__ )|| !defined(DPCT_COMPATIBILITY_TEMP )|| \ 58DPCT_COMPATIBILITY_TEMP < 750 ) 59/* unreachable on SYCL: the launcher refuses this device */ // AMD and pre-Turing builds: no mma.sync (the host keeps the old kernel there) 60#elif 0 // SYCL: Turing's m16n8k8 PTX (unreachable: the launcher refuses this device) 61 asmvolatile ("mma.sync.aligned.m16n8k8.row.col.f32.f16.f16.f32 {%0,%1,%2,%3}, {%4,%5}, {%6}, {%0,%1,%2,%3};\n" 62 :"+f" (c [0 ]),"+f" (c [1 ]),"+f" (c [2 ]),"+f" (c [3 ]) 63 :"r" (a [0 ]),"r" (a [1 ]),"r" (b [0 ])); 64 asmvolatile ("mma.sync.aligned.m16n8k8.row.col.f32.f16.f16.f32 {%0,%1,%2,%3}, {%4,%5}, {%6}, {%0,%1,%2,%3};\n" 65 :"+f" (c [0 ]),"+f" (c [1 ]),"+f" (c [2 ]),"+f" (c [3 ]) 66 :"r" (a [2 ]),"r" (a [3 ]),"r" (b [1 ])); 67#else 68#if defined(__SYCL_DEVICE_ONLY__ )&& defined(__NVPTX__ ) 69 asmvolatile ("mma.sync.aligned.m16n8k16.row.col.f32.f16.f16.f32 " 70"{%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, " 71"{%0,%1,%2,%3};\n" 72 :"+f" (c [0 ]),"+f" (c [1 ]),"+f" (c [2 ]),"+f" (c [3 ]) 73 :"r" (a [0 ]),"r" (a [1 ]),"r" (a [2 ]),"r" (a [3 ]),"r" (b [0 ]), 74"r" (b [1 ])); 75#else 76 { 77volatile void * d_mat_frag_ct1 [4 ]= {& c [0 ],& c [1 ],& c [2 ],& c [3 ]}; 78 sycl::vec < uint32_t ,4 > a_mat_frag_ct1 (a [0 ],a [1 ],a [2 ],a [3 ]); 79 sycl::vec < uint32_t ,2 > b_mat_frag_ct1 (b [0 ],b [1 ]); 80 sycl::vec < float ,4 > c_mat_frag_ct1 (c [0 ],c [1 ],c [2 ],c [3 ]); 81 dpct::experimental::matrix::mma < 16 ,8 ,16 , sycl::half ,float > ( 82reinterpret_cast < volatile void **> (d_mat_frag_ct1 ),& a_mat_frag_ct1 , 83& b_mat_frag_ct1 ,& c_mat_frag_ct1 ); 84 } 85#endif 86#endif 87} 88 89// Two int8 codes (low byte first) as an exact half2: 1024 + (c + 128) built in the mantissa, minus 1152. 90__dpct_inline__ uint32_t i8x2_to_h2 (uint32_t x ) { 91uint32_t y = ((x & 0xffu ) | ((x & 0xff00u ) <<8 )) ^0x00800080u ; 92y |=0x64006400u ; 93 sycl::half2 h = * reinterpret_cast < sycl::half2 *> (& y ); 94h = h - sycl::half2 ( 95 sycl::vec < float ,1 > (1152.f ) 96 .convert < sycl::half , sycl::rounding_mode::automatic > ()[0 ], 97 sycl::vec < float ,1 > (1152.f ) 98 .convert < sycl::half , sycl::rounding_mode::automatic > ()[0 ]); 99return * reinterpret_cast < uint32_t *> (& h ); 100} 101 102__dpct_inline__ uint32_t pack_h2 (float lo_k , 103float hi_k ) {// element k in the low half 104 sycl::half2 h = sycl::float2 (lo_k ,hi_k ) 105 .convert < sycl::half , sycl::rounding_mode::rte > (); 106return * reinterpret_cast < uint32_t *> (& h ); 107} 108 109// KV_MODE 1: int8 codes + fp16 scale per 64 values. KV_MODE 0: fp16 values (scales 1). 110// KV_MODE 3 (hybrid K8V4): K as mode 1, V as mode 0 - the row's q4_0 blocks are dequantized to fp16 at 111// gather, so everything downstream of the load is the mode-0 V path; the caller un-rotates the output. 112// KV_MODE 4 (Q4_0 K and V, `--kv q4_0`): mode 1 with a scale per 32 values - each q4_0 block's codes enter as exact 113// int8 (code - 8) and its fp16 scale is applied in FP32, as mode 1's are; the caller rotates q and un-rotates the 114// output (kv_q4.hpp). 115template < int KV_MODE > 116struct Smem { 117using KElem = 118typename std::conditional < KV_MODE == 0 , sycl::half ,int8_t > ::type ; 119using VElem = typename std::conditional < KV_MODE == 1 || KV_MODE == 4 , 120int8_t , sycl::half > ::type ; 121static constexpr int KROW = KV_MODE == 0 ?HD + 8 :HD + 16 ;// elements; 16-byte aligned rows, banks spread 122static constexpr int VROW = (KV_MODE == 1 || KV_MODE == 4 ) ?HD + 16 :HD + 8 ; 123static constexpr int NG = KV_MODE == 4 ?HD /QK4_0 :4 ;// scale groups per row (q4_0: 8 of 32, else 4 of 64) 124 sycl::half qh [16 ][QS ]; 125 sycl::half ql [16 ][QS ]; 126KElem k [CH ][KROW ]; 127VElem v [CH ][VROW ]; 128float ks [CH ][NG ]; 129float vs [CH ][NG ]; 130float s [16 ][CH + 1 ]; 131float qmax [THREADS /32 ]; 132float alpha [16 ]; 133float lsum [16 ]; 134float mrow [16 ]; 135long long row [CH ]; 136}; 137 138template < int KV_MODE > 139/* 140DPCT1110: The total declared local variable size in device function 141prompt_attn_kernel exceeds 128 bytes and may cause high register pressure. 142Consult with your hardware vendor to find the total register size available and 143adjust the code, or use smaller sub-group size to avoid high register pressure. 144*/ 145__dpct_inline__ void 146prompt_attn_kernel (const float * __restrict__q ,QsaAttnPools p , 147const int32_t * __restrict__ids , 148const int32_t * __restrict__steps ,int n_kv_heads , 149int page_size ,float scale_log2 ,float * __restrict__attn , 150int cap ,uint8_t * dpct_local ) { 151auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item < 3 > (); 152auto smem_raw = (unsigned char * )dpct_local ; 153Smem < KV_MODE >& S = * reinterpret_cast < Smem < KV_MODE >*> (smem_raw ); 154const int qi = item_ct1 .get_group (2 ),kvh = item_ct1 .get_group (1 ); 155const int n_head = n_kv_heads * G ; 156q += (size_t )qi * n_head * HD + (size_t )kvh * G * HD ; 157attn += (size_t )qi * n_head * HD + (size_t )kvh * G * HD ; 158ids += (size_t )qi * cap ; 159/* 160DPCT1098: The '*' expression is used instead of the __ldg call. These 161two expressions do not provide the exact same functionality. Check the 162generated code for potential precision and/or performance issues. 163*/ 164const int n = * (steps + (size_t )qi * kStepCount + kStepWidth ); 165const int t = item_ct1 .get_local_id (2 ),lane = t & 31 ,warp = t >>5 ; 166const int gid = lane >>2 ,tig = lane & 3 ; 167 168// q: 12 heads + 4 zero rows, scaled by a power of two that puts its largest value near 2^14 (exact, and the 169// lo halves stay out of FP16's subnormal range), then split into hi + lo halves 170float qm = 0.0f ; 171#pragma unroll 172for (int i = t ;i < G * HD ;i += THREADS ) 173qm = sycl::fmax (qm , sycl::fabs (q [i ])); 174#pragma unroll 175/* 176DPCT1108: '__shfl_xor_sync' was migrated with the experimental feature 177masked sub_group function which may not be supported by all compilers or 178runtimes. You may need to adjust the code. 179*/ 180for (int o = 16 ;o > 0 ;o >>=1 )qm = sycl::fmax ( 181qm , dpct::experimental::permute_sub_group_by_xor ( 1820xffffffffu , sycl::ext::oneapi::this_work_item::get_sub_group (), 183qm ,o )); 184if (lane == 0 )S .qmax [warp ]= qm ; 185/* 186DPCT1065: Consider replacing sycl::nd_item::barrier() with 187sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better 188performance if there is no access to global memory. 189*/ 190item_ct1 .barrier (); 191qm = sycl::fmax (sycl::fmax (S .qmax [0 ],S .qmax [1 ]), 192 sycl::fmax (S .qmax [2 ],S .qmax [3 ])); 193int qe = 0 ; 194/* 195DPCT1017: The sycl::frexp call is used instead of the frexpf call. 196These two calls do not provide exactly the same functionality. Check the 197potential precision and/or performance issues for the generated code. 198*/ 199if (qm > 0.0f ) sycl::frexp ( 200qm , sycl::address_space_cast < sycl::access::address_space::generic_space , 201 sycl::access::decorated::yes > ( 202& qe ));// qm < 2^qe 203const float qup = sycl::ldexp (1.0f ,14 - qe ), 204qdown = sycl::ldexp (scale_log2 ,qe - 14 ); 205for (int i = t ;i < 16 * HD ;i += THREADS ) { 206const int h = i /HD ,d = i %HD ; 207const float x = h < G ?q [(size_t )h * HD + d ]* qup :0.0f ; 208const sycl::half hi = 209 sycl::vec < float ,1 > (x ) 210 .convert < sycl::half , sycl::rounding_mode::rte > ()[0 ]; 211S .qh [h ][d ]= hi ; 212S .ql [h ][d ]= 213 sycl::vec < float ,1 > ( 214x - sycl::vec < sycl::half ,1 > (hi ) 215 .convert < float , sycl::rounding_mode::automatic > ()[0 ]) 216 .convert < sycl::half , sycl::rounding_mode::rte > ()[0 ]; 217 } 218if (t < 16 ) {S .mrow [t ]= - INFINITY ;S .lsum [t ]= 0.0f ; } 219 220float acc [8 ][4 ]; 221#pragma unroll 222for (int j = 0 ;j < 8 ;++ j )acc [j ][0 ]= acc [j ][1 ]= acc [j ][2 ]= acc [j ][3 ]= 0.0f ; 223 224for (int c0 = 0 ;c0 < n ;c0 += CH ) { 225const int nh = sycl::min (CH ,n - c0 ); 226if (t < CH ) { 227long long r = -1 ; 228if (t < nh ) { 229const int cell = ids [c0 + t ]; 230const long long page = (long long )p .page_table [cell /page_size ]; 231r = (page * n_kv_heads + kvh )* page_size + (cell %page_size ); 232 } 233S .row [t ]= r ; 234 } 235/* 236DPCT1118: SYCL group functions and algorithms must be encountered in 237converged control flow. You may need to adjust the code. 238*/ 239/* 240DPCT1065: Consider replacing sycl::nd_item::barrier() with 241sycl::nd_item::barrier(sycl::access::fence_space::local_space) for 242better performance if there is no access to global memory. 243*/ 244item_ct1 .barrier ();// rows ready; the previous chunk's p.v is done with 245// k, v, s 246// gather the chunk's K and V rows (16-byte pieces; K8V4's V as q4_0 blocks dequantized to fp16) 247// and their scales 248if constexpr (KV_MODE == 4 ) { 249// q4_0 K and V: one (K or V, cell, block) per item - the block's 16 code bytes (2-byte aligned: eight 250// 16-bit loads) become 32 exact int8 codes (element j in the low nibble of byte j, j + 16 in the high 251// one), its fp16 scale goes to ks/vs 252constexpr int BLKS = HD /QK4_0 ; 253constexpr int BYTES = BLKS * (int )sizeof (block_q4_0 ); 254for (int i = t ;i < 2 * CH * BLKS ;i += THREADS ) { 255const int kv = i / (CH * BLKS ),rem = i % (CH * BLKS ),c = rem /BLKS ,b = rem %BLKS ; 256const long long r = S .row [c ]; 257 sycl::uint4 lo = sycl::uint4 (0 ,0 ,0 ,0 ), 258hi = sycl::uint4 (0 ,0 ,0 ,0 ); 259float d = 0.0f ; 260if (r >=0 ) { 261const block_q4_0 * blk = reinterpret_cast < const block_q4_0 *> ((kv == 0 ?p .k_q4 :p .v_q4 )+ r * BYTES )+ b ; 262/* 263DPCT1098: The '*' expression is used instead of the 264__ldg call. These two expressions do not provide the exact 265same functionality. Check the generated code for potential 266precision and/or performance issues. 267*/ 268d = sycl::vec < sycl::half ,1 > ( 269 sycl::bit_cast < sycl::half ,unsigned short > (blk -> d )) 270 .convert < float , 271 sycl::rounding_mode::automatic > ()[0 ]; 272const uint16_t * q16 = reinterpret_cast < const uint16_t *> (blk -> qs ); 273uint32_t w [4 ]; 274#pragma unroll 275for (int j = 0 ;j < 4 ;++ j ) 276/* 277DPCT1098: The '*' expression is used instead of the 278__ldg call. These two expressions do not provide the 279exact same functionality. Check the generated code for 280potential precision and/or performance issues. 281*/ 282w [j ]= (uint32_t )* (q16 + 2 * j ) | 283 ((uint32_t )* (q16 + 2 * j + 1 ) <<16 ); 284// per byte: the low nibble minus 8 is element j, the high one minus 8 element j + 16 285lo = sycl::uint4 ( 286 dpct::vectorized_binary < sycl::uchar4 > ( 287w [0 ]& 0x0F0F0F0Fu ,0x08080808u , std::minus <> ()), 288 dpct::vectorized_binary < sycl::uchar4 > ( 289w [1 ]& 0x0F0F0F0Fu ,0x08080808u , std::minus <> ()), 290 dpct::vectorized_binary < sycl::uchar4 > ( 291w [2 ]& 0x0F0F0F0Fu ,0x08080808u , std::minus <> ()), 292 dpct::vectorized_binary < sycl::uchar4 > ( 293w [3 ]& 0x0F0F0F0Fu ,0x08080808u , std::minus <> ())); 294hi = sycl::uint4 (dpct::vectorized_binary < sycl::uchar4 > ( 295 (w [0 ] >>4 )& 0x0F0F0F0Fu ,0x08080808u , 296 std::minus <> ()), 297 dpct::vectorized_binary < sycl::uchar4 > ( 298 (w [1 ] >>4 )& 0x0F0F0F0Fu ,0x08080808u , 299 std::minus <> ()), 300 dpct::vectorized_binary < sycl::uchar4 > ( 301 (w [2 ] >>4 )& 0x0F0F0F0Fu ,0x08080808u , 302 std::minus <> ()), 303 dpct::vectorized_binary < sycl::uchar4 > ( 304 (w [3 ] >>4 )& 0x0F0F0F0Fu ,0x08080808u , 305 std::minus <> ())); 306 } 307int8_t * dst = kv == 0 ?& S .k [c ][b * QK4_0 ] :& S .v [c ][b * QK4_0 ]; 308reinterpret_cast < sycl::uint4 *> (dst )[0 ]= lo ; 309reinterpret_cast < sycl::uint4 *> (dst )[1 ]= hi ; 310 (kv == 0 ?S .ks :S .vs )[c ][b ]= d ; 311 } 312 }else { 313constexpr int KPIECES = HD * (int )sizeof (typename Smem < KV_MODE > ::KElem ) /16 ;// per K row 314for (int i = t ;i < CH * KPIECES ;i += THREADS ) { 315const int c = i /KPIECES ,pc = i %KPIECES ; 316const long long r = S .row [c ]; 317 sycl::uint4 kx = sycl::uint4 (0 ,0 ,0 ,0 ); 318if (r >=0 ) { 319if constexpr (KV_MODE == 0 ) 320/* 321DPCT1098: The '*' expression is used instead of the 322__ldg call. These two expressions do not provide the 323exact same functionality. Check the generated code for 324potential precision and/or performance issues. 325*/ 326kx = * (reinterpret_cast < const sycl::uint4 *> (p .k_pool + 327r * HD )+ 328pc ); 329else // modes 1 and 3: the K side is INT8 330/* 331DPCT1098: The '*' expression is used instead of the 332__ldg call. These two expressions do not provide the 333exact same functionality. Check the generated code for 334potential precision and/or performance issues. 335*/ 336kx = * (reinterpret_cast < const sycl::uint4 *> (p .k_q + 337r * HD )+ 338pc ); 339 } 340* reinterpret_cast < sycl::uint4 *> ( 341reinterpret_cast < unsigned char *> (& S .k [c ][0 ])+ pc * 16 )= 342kx ; 343 } 344if constexpr (KV_MODE == 3 ) {// V: dequantize the row's q4_0 blocks straight into the fp16 V row 345constexpr int BLKS = HD /QK4_0 ; 346constexpr int BYTES = BLKS * (int )sizeof (block_q4_0 ); 347for (int i = t ;i < CH * BLKS ;i += THREADS ) { 348const int c = i /BLKS ,b = i %BLKS ; 349const long long r = S .row [c ]; 350#pragma unroll 351for (int j = 0 ;j < QK4_0 ;++ j ) 352S .v [c ][b * QK4_0 + j ]= sycl::half (0 ); 353if (r >=0 ) { 354const block_q4_0 * blk = reinterpret_cast < const block_q4_0 *> (p .v_q4 + r * BYTES )+ b ; 355const float d = 356 sycl::vec < sycl::half ,1 > ( 357 sycl::bit_cast < sycl::half ,unsigned short > ( 358blk -> d )) 359 .convert < float , 360 sycl::rounding_mode::automatic > ()[0 ]; 361#pragma unroll 362for (int j = 0 ;j < QK4_0 /2 ;++ j ) { 363S .v [c ][b * QK4_0 + j ]= 364 sycl::vec < float ,1 > ( 365 (float )((int )(blk -> qs [j ]& 0x0F )- 8 )* d ) 366 .convert < sycl::half , 367 sycl::rounding_mode::rte > ()[0 ]; 368S .v [c ][b * QK4_0 + j + QK4_0 /2 ]= 369 sycl::vec < float ,1 > ( 370 (float )((int )(blk -> qs [j ] >>4 )- 8 )* d ) 371 .convert < sycl::half , 372 sycl::rounding_mode::rte > ()[0 ]; 373 } 374 } 375 } 376 }else { 377constexpr int VPIECES = HD * (int )sizeof (typename Smem < KV_MODE > ::VElem ) /16 ;// per V row 378for (int i = t ;i < CH * VPIECES ;i += THREADS ) { 379const int c = i /VPIECES ,pc = i %VPIECES ; 380const long long r = S .row [c ]; 381 sycl::uint4 vx = sycl::uint4 (0 ,0 ,0 ,0 ); 382if (r >=0 ) { 383if constexpr (KV_MODE == 1 ) 384/* 385DPCT1098: The '*' expression is used instead of 386the __ldg call. These two expressions do not provide 387the exact same functionality. Check the generated 388code for potential precision and/or performance 389issues. 390*/ 391vx = * (reinterpret_cast < const sycl::uint4 *> ( 392p .v_q + r * HD )+ 393pc ); 394else 395/* 396DPCT1098: The '*' expression is used instead of 397the __ldg call. These two expressions do not provide 398the exact same functionality. Check the generated 399code for potential precision and/or performance 400issues. 401*/ 402vx = * (reinterpret_cast < const sycl::uint4 *> ( 403p .v_pool + r * HD )+ 404pc ); 405 } 406* reinterpret_cast < sycl::uint4 *> ( 407reinterpret_cast < unsigned char *> (& S .v [c ][0 ])+ 408pc * 16 )= vx ; 409 } 410 } 411for (int i = t ;i < CH * 4 ;i += THREADS ) { 412const int c = i /4 ,g = i %4 ; 413const long long r = S .row [c ]; 414float a = 0.0f ,b = 0.0f ; 415if (r >=0 ) { 416if constexpr (KV_MODE == 1 ) { 417a = sycl::vec < sycl::half ,1 > ( 418 sycl::bit_cast < sycl::half ,unsigned short > ( 419p .k_scale [r * (HD /KV_Q8_GROUP )+ g ])) 420 .convert < float , 421 sycl::rounding_mode::automatic > ()[0 ]; 422b = sycl::vec < sycl::half ,1 > ( 423 sycl::bit_cast < sycl::half ,unsigned short > ( 424p .v_scale [r * (HD /KV_Q8_GROUP )+ g ])) 425 .convert < float , 426 sycl::rounding_mode::automatic > ()[0 ]; 427 }else if constexpr (KV_MODE == 3 ) {// K as int8, V dequantized to fp16 (scale 1) 428a = sycl::vec < sycl::half ,1 > ( 429 sycl::bit_cast < sycl::half ,unsigned short > ( 430p .k_scale [r * (HD /KV_Q8_GROUP )+ g ])) 431 .convert < float , 432 sycl::rounding_mode::automatic > ()[0 ]; 433b = 1.0f ; 434 }else { 435a = b = 1.0f ; 436 } 437 } 438S .ks [c ][g ]= a ; 439S .vs [c ][g ]= b ; 440 } 441 } 442/* 443DPCT1118: SYCL group functions and algorithms must be encountered in 444converged control flow. You may need to adjust the code. 445*/ 446/* 447DPCT1065: Consider replacing sycl::nd_item::barrier() with 448sycl::nd_item::barrier(sycl::access::fence_space::local_space) for 449better performance if there is no access to global memory. 450*/ 451item_ct1 .barrier (); 452// scores: warp w takes cells 8w..8w+7 (one n-tile) over all 256 dims, per scale group (64 dims; q4_0's 32) 453constexpr int NG = Smem < KV_MODE > ::NG ,KPG = HD /16 /NG ;// groups per row, 16-dim MMA steps per group 454#pragma unroll 455for (int nt = 0 ;nt < CH /32 ;++ nt ) { 456const int cb = (warp + 4 * nt )* 8 ; 457float sc [4 ]= {0.f ,0.f ,0.f ,0.f }; 458#pragma unroll 459for (int g = 0 ;g < NG ;++ g ) { 460float tg [4 ]= {0.f ,0.f ,0.f ,0.f }; 461#pragma unroll 462for (int kk = 0 ;kk < KPG ;++ kk ) { 463const int k0 = (g * KPG + kk )* 16 ; 464uint32_t ah [4 ],al [4 ],b [2 ]; 465ah [0 ]= * reinterpret_cast < const uint32_t *> (& S .qh [gid ][k0 + 2 * tig ]); 466ah [1 ]= * reinterpret_cast < const uint32_t *> (& S .qh [gid + 8 ][k0 + 2 * tig ]); 467ah [2 ]= * reinterpret_cast < const uint32_t *> (& S .qh [gid ][k0 + 2 * tig + 8 ]); 468ah [3 ]= * reinterpret_cast < const uint32_t *> (& S .qh [gid + 8 ][k0 + 2 * tig + 8 ]); 469al [0 ]= * reinterpret_cast < const uint32_t *> (& S .ql [gid ][k0 + 2 * tig ]); 470al [1 ]= * reinterpret_cast < const uint32_t *> (& S .ql [gid + 8 ][k0 + 2 * tig ]); 471al [2 ]= * reinterpret_cast < const uint32_t *> (& S .ql [gid ][k0 + 2 * tig + 8 ]); 472al [3 ]= * reinterpret_cast < const uint32_t *> (& S .ql [gid + 8 ][k0 + 2 * tig + 8 ]); 473if constexpr (KV_MODE != 0 ) {// modes 1 and 3: the K side is INT8 codes 474b [0 ]= i8x2_to_h2 (* reinterpret_cast < const uint16_t *> (& S .k [cb + gid ][k0 + 2 * tig ])); 475b [1 ]= i8x2_to_h2 (* reinterpret_cast < const uint16_t *> (& S .k [cb + gid ][k0 + 2 * tig + 8 ])); 476 }else { 477b [0 ]= * reinterpret_cast < const uint32_t *> (& S .k [cb + gid ][k0 + 2 * tig ]); 478b [1 ]= * reinterpret_cast < const uint32_t *> (& S .k [cb + gid ][k0 + 2 * tig + 8 ]); 479 } 480mma16816 (tg ,ah ,b ); 481#ifndef D1_NO_QLO 482mma16816 (tg ,al ,b ); 483#endif 484 } 485const float s0 = S .ks [cb + 2 * tig ][g ],s1 = S .ks [cb + 2 * tig + 1 ][g ]; 486sc [0 ]= sycl::fma (tg [0 ], (float )s0 ,sc [0 ]); 487sc [1 ]= sycl::fma (tg [1 ], (float )s1 ,sc [1 ]); 488sc [2 ]= sycl::fma (tg [2 ], (float )s0 ,sc [2 ]); 489sc [3 ]= sycl::fma (tg [3 ], (float )s1 ,sc [3 ]); 490 } 491const int c = cb + 2 * tig ; 492S .s [gid ][c ]= c < nh ?sc [0 ]* qdown :- INFINITY ; 493S .s [gid ][c + 1 ]= c + 1 < nh ?sc [1 ]* qdown :- INFINITY ; 494S .s [gid + 8 ][c ]= c < nh ?sc [2 ]* qdown :- INFINITY ; 495S .s [gid + 8 ][c + 1 ]= c + 1 < nh ?sc [3 ]* qdown :- INFINITY ; 496 } 497/* 498DPCT1118: SYCL group functions and algorithms must be encountered in 499converged control flow. You may need to adjust the code. 500*/ 501/* 502DPCT1065: Consider replacing sycl::nd_item::barrier() with 503sycl::nd_item::barrier(sycl::access::fence_space::local_space) for 504better performance if there is no access to global memory. 505*/ 506item_ct1 .barrier (); 507// online softmax: row t/8, 4 cells per thread, 8 threads per row (lanes 8r..8r+7 of a warp) 508 { 509constexpr int PER = CH /8 ; 510const int r = t >>3 ,sub = t & 7 ; 511float x [PER ],mx = - INFINITY ; 512#pragma unroll 513for (int j = 0 ;j < PER ;++ j ) { 514x [j ]= S .s [r ][sub * PER + j ];mx = sycl::fmax (mx ,x [j ]); 515 } 516#pragma unroll 517/* 518DPCT1108: '__shfl_xor_sync' was migrated with the experimental 519feature masked sub_group function which may not be supported by all 520compilers or runtimes. You may need to adjust the code. 521*/ 522for (int o = 1 ;o < 8 ;o <<=1 )mx = sycl::fmax ( 523mx , 524 dpct::experimental::permute_sub_group_by_xor ( 5250xffffffffu , 526 sycl::ext::oneapi::this_work_item::get_sub_group (),mx ,o )); 527const float m_old = S .mrow [r ]; 528const float m_new = sycl::fmax (m_old ,mx ); 529float sum = 0.0f ; 530#pragma unroll 531for (int j = 0 ;j < PER ;++ j ) { 532const float e = 533x [j ]== - INFINITY ?0.0f : sycl::exp2 (x [j ]- m_new ); 534S .s [r ][sub * PER + j ]= e ; 535sum += e ; 536 } 537#pragma unroll 538/* 539DPCT1108: '__shfl_xor_sync' was migrated with the experimental 540feature masked sub_group function which may not be supported by all 541compilers or runtimes. You may need to adjust the code. 542*/ 543for (int o = 1 ;o < 8 ;o <<=1 )sum += 544 dpct::experimental::permute_sub_group_by_xor ( 5450xffffffffu , 546 sycl::ext::oneapi::this_work_item::get_sub_group (),sum ,o ); 547 sycl::group_barrier ( 548 sycl::ext::oneapi::this_work_item::get_sub_group ()); 549if (sub == 0 ) { 550const float a = 551m_old == - INFINITY ?0.0f : sycl::exp2 (m_old - m_new ); 552S .alpha [r ]= a ; 553S .lsum [r ]= sycl::fma (S .lsum [r ], (float )a ,sum ); 554S .mrow [r ]= m_new ; 555 } 556 } 557/* 558DPCT1118: SYCL group functions and algorithms must be encountered in 559converged control flow. You may need to adjust the code. 560*/ 561/* 562DPCT1065: Consider replacing sycl::nd_item::barrier() with 563sycl::nd_item::barrier(sycl::access::fence_space::local_space) for 564better performance if there is no access to global memory. 565*/ 566item_ct1 .barrier (); 567// p.v: warp w owns dims [64w, 64w+64), which is int8 scale group w (q4_0: groups 2w and 2w+1, four n-tiles 568// each). A group's scale is folded into p relative to the chunk's largest magnitude (q4_0's scales are signed: 569// ggml's d = max / -8), times 2^14 (|p'| <= 2^14: inside FP16's range, its lo half out of the subnormals); the 570// chunk's sum is then added to the running one in FP32 with the factor taken back out 571 { 572constexpr int GPW = NG /4 ,JPG = 8 /GPW ;// scale groups per warp, n-tiles per group 573float vdown_g [GPW ]; 574float tmp [8 ][4 ]; 575#pragma unroll 576for (int j = 0 ;j < 8 ;++ j )tmp [j ][0 ]= tmp [j ][1 ]= tmp [j ][2 ]= tmp [j ][3 ]= 0.0f ; 577#pragma unroll 578for (int gi = 0 ;gi < GPW ;++ gi ) { 579const int vg = warp * GPW + gi ; 580float vmax = 0.0f ; 581#pragma unroll 582for (int c = lane ;c < CH ;c += 32 ) 583vmax = sycl::fmax (vmax , sycl::fabs (S .vs [c ][vg ])); 584#pragma unroll 585/* 586DPCT1108: '__shfl_xor_sync' was migrated with the experimental 587feature masked sub_group function which may not be supported by all 588compilers or runtimes. You may need to adjust the code. 589*/ 590for (int o = 16 ;o > 0 ;o >>=1 )vmax = sycl::fmax ( 591vmax , dpct::experimental::permute_sub_group_by_xor ( 5920xffffffffu , 593 sycl::ext::oneapi::this_work_item::get_sub_group (), 594vmax ,o )); 595const float vup = vmax > 0.0f ?16384.0f /vmax :0.0f ; 596vdown_g [gi ]= vmax * (1.0f /16384.0f ); 597#pragma unroll 598for (int ks = 0 ;ks < CH /16 ;++ ks ) { 599const int cA = ks * 16 + 2 * tig ,cB = cA + 8 ; 600const float w0 = S .vs [cA ][vg ]* vup ,w1 = S .vs [cA + 1 ][vg ]* vup ,w2 = S .vs [cB ][vg ]* vup , 601w3 = S .vs [cB + 1 ][vg ]* vup ; 602const float p00 = S .s [gid ][cA ]* w0 ,p01 = S .s [gid ][cA + 1 ]* w1 ; 603const float p10 = S .s [gid + 8 ][cA ]* w0 ,p11 = S .s [gid + 8 ][cA + 1 ]* w1 ; 604const float p02 = S .s [gid ][cB ]* w2 ,p03 = S .s [gid ][cB + 1 ]* w3 ; 605const float p12 = S .s [gid + 8 ][cB ]* w2 ,p13 = S .s [gid + 8 ][cB + 1 ]* w3 ; 606uint32_t ah [4 ],al [4 ]; 607ah [0 ]= pack_h2 (p00 ,p01 ); 608ah [1 ]= pack_h2 (p10 ,p11 ); 609ah [2 ]= pack_h2 (p02 ,p03 ); 610ah [3 ]= pack_h2 (p12 ,p13 ); 611 { 612const sycl::half2 * h = 613reinterpret_cast < const sycl::half2 *> (ah ); 614 sycl::float2 f ; 615f = h [0 ].template convert < float , 616 sycl::rounding_mode::automatic > (); 617al [0 ]= pack_h2 (p00 - f .x (),p01 - f .y ()); 618f = h [1 ].template convert < float , 619 sycl::rounding_mode::automatic > (); 620al [1 ]= pack_h2 (p10 - f .x (),p11 - f .y ()); 621f = h [2 ].template convert < float , 622 sycl::rounding_mode::automatic > (); 623al [2 ]= pack_h2 (p02 - f .x (),p03 - f .y ()); 624f = h [3 ].template convert < float , 625 sycl::rounding_mode::automatic > (); 626al [3 ]= pack_h2 (p12 - f .x (),p13 - f .y ()); 627 } 628#pragma unroll 629for (int jj = 0 ;jj < JPG ;++ jj ) { 630const int j = gi * JPG + jj ; 631const int d = warp * 64 + j * 8 + gid ; 632uint32_t b [2 ]; 633if constexpr (KV_MODE == 1 || KV_MODE == 4 ) { 634const uint32_t x0 = (uint8_t )S .v [cA ][d ] | ((uint32_t ) (uint8_t )S .v [cA + 1 ][d ] <<8 ); 635const uint32_t x1 = (uint8_t )S .v [cB ][d ] | ((uint32_t ) (uint8_t )S .v [cB + 1 ][d ] <<8 ); 636b [0 ]= i8x2_to_h2 (x0 ); 637b [1 ]= i8x2_to_h2 (x1 ); 638 }else { 639const sycl::half2 h0 = 640 sycl::half2 (S .v [cA ][d ],S .v [cA + 1 ][d ]); 641const sycl::half2 h1 = 642 sycl::half2 (S .v [cB ][d ],S .v [cB + 1 ][d ]); 643b [0 ]= * reinterpret_cast < const uint32_t *> (& h0 ); 644b [1 ]= * reinterpret_cast < const uint32_t *> (& h1 ); 645 } 646mma16816 (tmp [j ],ah ,b ); 647#ifndef D1_NO_PLO 648mma16816 (tmp [j ],al ,b ); 649#endif 650 } 651 } 652 } 653const float a0 = S .alpha [gid ],a1 = S .alpha [gid + 8 ]; 654#pragma unroll 655for (int j = 0 ;j < 8 ;++ j ) { 656const float vdown = vdown_g [j /JPG ]; 657acc [j ][0 ]= sycl::fma (acc [j ][0 ], (float )a0 ,tmp [j ][0 ]* vdown ); 658acc [j ][1 ]= sycl::fma (acc [j ][1 ], (float )a0 ,tmp [j ][1 ]* vdown ); 659acc [j ][2 ]= sycl::fma (acc [j ][2 ], (float )a1 ,tmp [j ][2 ]* vdown ); 660acc [j ][3 ]= sycl::fma (acc [j ][3 ], (float )a1 ,tmp [j ][3 ]* vdown ); 661 } 662 } 663 } 664/* 665DPCT1065: Consider replacing sycl::nd_item::barrier() with 666sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better 667performance if there is no access to global memory. 668*/ 669item_ct1 .barrier (); 670const float l0 = S .lsum [gid ],l1 = S .lsum [gid + 8 ]; 671const float i0 = l0 > 0.0f ?1.0f /l0 :0.0f ,i1 = l1 > 0.0f ?1.0f /l1 :0.0f ; 672#pragma unroll 673for (int j = 0 ;j < 8 ;++ j ) { 674const int d = warp * 64 + j * 8 + 2 * tig ; 675* reinterpret_cast < sycl::float2 *> (attn + (size_t )gid * HD + d )= 676 sycl::float2 (acc [j ][0 ]* i0 ,acc [j ][1 ]* i0 ); 677if (gid + 8 < G ) 678* reinterpret_cast < sycl::float2 *> (attn + (size_t )(gid + 8 )* HD + 679d )= 680 sycl::float2 (acc [j ][2 ]* i1 ,acc [j ][3 ]* i1 ); 681 } 682} 683 684// ---- v2 (int8 KV): warp w owns dims [64w, 64w+64) for both q.k and p.v, which is also int8 scale group w. So a 685// warp needs only its own 64-byte slice of each K and V row: it gathers it itself with cp.async into its own 686// double-buffered stage while it computes the previous chunk, and q stays in registers. Only the q.k partial sums 687// (one per dim group) cross warps, and they are added in a fixed order: the result is deterministic. 688constexpr int CH2 = 32 ; 689 690struct Smem2 { 691int8_t kv [2 ][4 ][2 ][CH2 ][64 ];// stage, warp, K/V, cell, 64 dims in 16-byte pieces XOR-swizzled by the cell 692float sc [2 ][4 ][2 ][CH2 ];// stage, warp, K/V scale of the cell for the warp's group 693float part [4 ][16 ][CH2 + 1 ];// q.k per dim group 694float p [16 ][CH2 + 1 ]; 695float qmax [4 ]; 696float alpha [16 ]; 697float lsum [16 ]; 698float mrow [16 ]; 699}; 700 701__dpct_inline__ int 702swz (int cell ,int byte ) {// byte offset of (cell, byte) in a stage slice 703return cell * 64 + ((((byte >>4 ) ^ (cell >>1 ))& 3 ) <<4 )+ (byte & 15 ); 704} 705__dpct_inline__ void cp_async16 (void * smem ,const void * gmem ,bool valid ) { 706#if !STRATA_PA_SM80 707/* unreachable on SYCL: the launcher refuses this device */ 708#else 709auto sa = smem ; 710/* 711DPCT1053: Migration of device assembly code is not supported. 712*/ 713 asmvolatile ("cp.async.cg.shared.global [%0], [%1], 16, %2;\n" ::"r" (sa ), 714"l" (gmem ),"r" (valid ?16 :0 )); 715#endif 716} 717__dpct_inline__ void cp_async_commit () { 718#if STRATA_PA_SM80 719#if defined(__SYCL_DEVICE_ONLY__ )&& defined(__NVPTX__ ) 720 asmvolatile ("cp.async.commit_group;\n" ::); 721#else 722 723#endif 724#endif 725} 726__dpct_inline__ void cp_async_wait1 () { 727#if STRATA_PA_SM80 728#if defined(__SYCL_DEVICE_ONLY__ )&& defined(__NVPTX__ ) 729 asmvolatile ("cp.async.wait_group 1;\n" ::); 730#else 731 732#endif 733#endif 734} 735 736/* 737DPCT1110: The total declared local variable size in device function 738prompt_attn_i8_kernel exceeds 128 bytes and may cause high register pressure. 739Consult with your hardware vendor to find the total register size available and 740adjust the code, or use smaller sub-group size to avoid high register pressure. 741*/ 742__dpct_inline__ void 743prompt_attn_i8_kernel (const float * __restrict__q ,QsaAttnPools p , 744const int32_t * __restrict__ids , 745const int32_t * __restrict__steps ,int n_kv_heads , 746int page_size ,float scale_log2 ,float * __restrict__attn , 747int cap ,uint8_t * dpct_local ) { 748auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item < 3 > (); 749auto smem_raw = (unsigned char * )dpct_local ; 750Smem2 & S = * reinterpret_cast < Smem2 *> (smem_raw ); 751const int qi = item_ct1 .get_group (2 ),kvh = item_ct1 .get_group (1 ); 752const int n_head = n_kv_heads * G ; 753q += (size_t )qi * n_head * HD + (size_t )kvh * G * HD ; 754attn += (size_t )qi * n_head * HD + (size_t )kvh * G * HD ; 755ids += (size_t )qi * cap ; 756/* 757DPCT1098: The '*' expression is used instead of the __ldg call. These 758two expressions do not provide the exact same functionality. Check the 759generated code for potential precision and/or performance issues. 760*/ 761const int n = * (steps + (size_t )qi * kStepCount + kStepWidth ); 762const int t = item_ct1 .get_local_id (2 ),lane = t & 31 ,warp = t >>5 ; 763const int gid = lane >>2 ,tig = lane & 3 ; 764const int dim0 = warp * 64 ; 765 766// q: the power-of-two prescale over all 12 heads (as v1), then this warp's 64 dims as hi/lo A fragments 767float qm = 0.0f ; 768#pragma unroll 769for (int i = t ;i < G * HD ;i += THREADS ) 770qm = sycl::fmax (qm , sycl::fabs (q [i ])); 771#pragma unroll 772/* 773DPCT1108: '__shfl_xor_sync' was migrated with the experimental feature 774masked sub_group function which may not be supported by all compilers or 775runtimes. You may need to adjust the code. 776*/ 777for (int o = 16 ;o > 0 ;o >>=1 )qm = sycl::fmax ( 778qm , dpct::experimental::permute_sub_group_by_xor ( 7790xffffffffu , sycl::ext::oneapi::this_work_item::get_sub_group (), 780qm ,o )); 781if (lane == 0 )S .qmax [warp ]= qm ; 782if (t < 16 ) {S .mrow [t ]= - INFINITY ;S .lsum [t ]= 0.0f ; } 783/* 784DPCT1065: Consider replacing sycl::nd_item::barrier() with 785sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better 786performance if there is no access to global memory. 787*/ 788item_ct1 .barrier (); 789qm = sycl::fmax (sycl::fmax (S .qmax [0 ],S .qmax [1 ]), 790 sycl::fmax (S .qmax [2 ],S .qmax [3 ])); 791int qe = 0 ; 792/* 793DPCT1017: The sycl::frexp call is used instead of the frexpf call. 794These two calls do not provide exactly the same functionality. Check the 795potential precision and/or performance issues for the generated code. 796*/ 797if (qm > 0.0f ) sycl::frexp ( 798qm , sycl::address_space_cast < sycl::access::address_space::generic_space , 799 sycl::access::decorated::yes > (& qe )); 800const float qup = sycl::ldexp (1.0f ,14 - qe ), 801qdown = sycl::ldexp (scale_log2 ,qe - 14 ); 802uint32_t qh [4 ][4 ],ql [4 ][4 ]; 803#pragma unroll 804for (int kk = 0 ;kk < 4 ;++ kk ) { 805#pragma unroll 806for (int r = 0 ;r < 4 ;++ r ) { 807const int row = gid + (r & 1 )* 8 ,col = dim0 + kk * 16 + 2 * tig + (r >>1 )* 8 ; 808 sycl::float2 x = sycl::float2 (0.f ,0.f ); 809if (row < G )x = * reinterpret_cast < const sycl::float2 *> ( 810q + (size_t )row * HD + col ); 811x .x () *=qup ; 812x .y () *=qup ; 813const sycl::half2 hi = 814 sycl::float2 (x .x (),x .y ()) 815 .convert < sycl::half , sycl::rounding_mode::rte > (); 816const sycl::float2 hf = 817hi .template convert < float , sycl::rounding_mode::automatic > (); 818const sycl::half2 lo = 819 sycl::float2 (x .x ()- hf .x (),x .y ()- hf .y ()) 820 .convert < sycl::half , sycl::rounding_mode::rte > (); 821qh [kk ][r ]= * reinterpret_cast < const uint32_t *> (& hi ); 822ql [kk ][r ]= * reinterpret_cast < const uint32_t *> (& lo ); 823 } 824 } 825 826// the chunk pipeline: cells two chunks ahead, their pool rows one chunk ahead, the data (cp.async) one ahead 827const int n_chunks = (n + CH2 - 1 ) /CH2 ; 828/* 829DPCT1098: The '*' expression is used instead of the __ldg call. These 830two expressions do not provide the exact same functionality. Check the 831generated code for potential precision and/or performance issues. 832*/ 833auto cell_of = [& ](int c )-> int { 834return c < n ?* (ids + c ) :-1 ; 835 }; 836auto row_of = [& ](int cell )-> long long { 837if (cell < 0 )return -1 ; 838/* 839DPCT1098: The '*' expression is used instead of the __ldg call. 840These two expressions do not provide the exact same functionality. Check 841the generated code for potential precision and/or performance issues. 842*/ 843const long long page = (long long )* (p .page_table + cell /page_size ); 844return (page * n_kv_heads + kvh )* page_size + (cell %page_size ); 845 }; 846auto issue = [& ](long long r ,int st ,float & ksr ,float & vsr ) { 847#pragma unroll 848for (int j = 0 ;j < 4 ;++ j ) { 849const int idx = lane + 32 * j ,cell = idx >>2 ,pc = idx & 3 ; 850/* 851DPCT1108: '__shfl_sync' was migrated with the experimental 852feature masked sub_group function which may not be supported by all 853compilers or runtimes. You may need to adjust the code. 854*/ 855/* 856DPCT1121: Make sure that the "r" which is used in the SYCL group 857function/algorithm is initialized. 858*/ 859const long long rr = dpct::experimental::select_from_sub_group ( 8600xffffffffu , sycl::ext::oneapi::this_work_item::get_sub_group (), 861r ,cell ); 862const bool ok = rr >=0 ; 863const size_t off = ok ? (size_t )rr * HD + dim0 + pc * 16 :0 ; 864cp_async16 (& S .kv [st ][warp ][0 ][0 ][0 ]+ swz (cell ,pc * 16 ),p .k_q + off ,ok ); 865cp_async16 (& S .kv [st ][warp ][1 ][0 ][0 ]+ swz (cell ,pc * 16 ),p .v_q + off ,ok ); 866 } 867/* 868DPCT1098: The '*' expression is used instead of the __ldg call. 869These two expressions do not provide the exact same functionality. Check 870the generated code for potential precision and/or performance issues. 871*/ 872ksr = r >=0 ? sycl::vec < sycl::half ,1 > ( 873 sycl::bit_cast < sycl::half ,unsigned short > ( 874* (p .k_scale + r * (HD /KV_Q8_GROUP )+ warp ))) 875 .convert < float , sycl::rounding_mode::automatic > ()[0 ] 876 :0.0f ; 877/* 878DPCT1098: The '*' expression is used instead of the __ldg call. 879These two expressions do not provide the exact same functionality. Check 880the generated code for potential precision and/or performance issues. 881*/ 882vsr = r >=0 ? sycl::vec < sycl::half ,1 > ( 883 sycl::bit_cast < sycl::half ,unsigned short > ( 884* (p .v_scale + r * (HD /KV_Q8_GROUP )+ warp ))) 885 .convert < float , sycl::rounding_mode::automatic > ()[0 ] 886 :0.0f ; 887 }; 888float ksn ,vsn ; 889issue (row_of (cell_of (lane )),0 ,ksn ,vsn ); 890cp_async_commit (); 891S .sc [0 ][warp ][0 ][lane ]= ksn ; 892S .sc [0 ][warp ][1 ][lane ]= vsn ; 893long long r_next = row_of (cell_of (CH2 + lane )); 894int cell_next2 = cell_of (2 * CH2 + lane ); 895 896float acc [8 ][4 ]; 897#pragma unroll 898for (int j = 0 ;j < 8 ;++ j )acc [j ][0 ]= acc [j ][1 ]= acc [j ][2 ]= acc [j ][3 ]= 0.0f ; 899 900for (int ci = 0 ;ci < n_chunks ;++ ci ) { 901const int st = ci & 1 ,c0 = ci * CH2 ; 902const bool more = ci + 1 < n_chunks ; 903if (more )issue (r_next ,st ^1 ,ksn ,vsn ); 904cp_async_commit (); 905r_next = row_of (cell_next2 ); 906cell_next2 = cell_of ((ci + 3 )* CH2 + lane ); 907cp_async_wait1 (); 908 sycl::group_barrier (sycl::ext::oneapi::this_work_item::get_sub_group ()); 909const int8_t * K = & S .kv [st ][warp ][0 ][0 ][0 ]; 910const int8_t * V = & S .kv [st ][warp ][1 ][0 ][0 ]; 911// q.k over this warp's 64 dims, times the cell's K scale for this group 912#pragma unroll 913for (int nt = 0 ;nt < CH2 /8 ;++ nt ) { 914float tg [4 ]= {0.f ,0.f ,0.f ,0.f }; 915const int cell = nt * 8 + gid ; 916#pragma unroll 917for (int kk = 0 ;kk < 4 ;++ kk ) { 918uint32_t b [2 ]; 919b [0 ]= i8x2_to_h2 (* reinterpret_cast < const uint16_t *> (K + swz (cell ,kk * 16 + 2 * tig ))); 920b [1 ]= i8x2_to_h2 (* reinterpret_cast < const uint16_t *> (K + swz (cell ,kk * 16 + 2 * tig + 8 ))); 921mma16816 (tg ,qh [kk ],b ); 922mma16816 (tg ,ql [kk ],b ); 923 } 924const int c = nt * 8 + 2 * tig ; 925const float s0 = S .sc [st ][warp ][0 ][c ],s1 = S .sc [st ][warp ][0 ][c + 1 ]; 926S .part [warp ][gid ][c ]= tg [0 ]* s0 ; 927S .part [warp ][gid ][c + 1 ]= tg [1 ]* s1 ; 928S .part [warp ][gid + 8 ][c ]= tg [2 ]* s0 ; 929S .part [warp ][gid + 8 ][c + 1 ]= tg [3 ]* s1 ; 930 } 931/* 932DPCT1118: SYCL group functions and algorithms must be encountered in 933converged control flow. You may need to adjust the code. 934*/ 935/* 936DPCT1065: Consider replacing sycl::nd_item::barrier() with 937sycl::nd_item::barrier(sycl::access::fence_space::local_space) for 938better performance if there is no access to global memory. 939*/ 940item_ct1 .barrier (); 941// online softmax over the four groups' sum (fixed order): row t/8, 4 cells per thread 942 { 943const int r = t >>3 ,sub = t & 7 ; 944float x [4 ],mx = - INFINITY ; 945#pragma unroll 946for (int j = 0 ;j < 4 ;++ j ) { 947const int c = sub * 4 + j ; 948x [j ]= c0 + c < n ? (((S .part [0 ][r ][c ]+ S .part [1 ][r ][c ])+ S .part [2 ][r ][c ])+ S .part [3 ][r ][c ])* qdown 949 :- INFINITY ; 950mx = sycl::fmax (mx ,x [j ]); 951 } 952#pragma unroll 953/* 954DPCT1108: '__shfl_xor_sync' was migrated with the experimental 955feature masked sub_group function which may not be supported by all 956compilers or runtimes. You may need to adjust the code. 957*/ 958for (int o = 1 ;o < 8 ;o <<=1 )mx = sycl::fmax ( 959mx , 960 dpct::experimental::permute_sub_group_by_xor ( 9610xffffffffu , 962 sycl::ext::oneapi::this_work_item::get_sub_group (),mx ,o )); 963const float m_old = S .mrow [r ]; 964const float m_new = sycl::fmax (m_old ,mx ); 965float sum = 0.0f ; 966#pragma unroll 967for (int j = 0 ;j < 4 ;++ j ) { 968const float e = 969x [j ]== - INFINITY ?0.0f : sycl::exp2 (x [j ]- m_new ); 970S .p [r ][sub * 4 + j ]= e ; 971sum += e ; 972 } 973#pragma unroll 974/* 975DPCT1108: '__shfl_xor_sync' was migrated with the experimental 976feature masked sub_group function which may not be supported by all 977compilers or runtimes. You may need to adjust the code. 978*/ 979for (int o = 1 ;o < 8 ;o <<=1 )sum += 980 dpct::experimental::permute_sub_group_by_xor ( 9810xffffffffu , 982 sycl::ext::oneapi::this_work_item::get_sub_group (),sum ,o ); 983 sycl::group_barrier ( 984 sycl::ext::oneapi::this_work_item::get_sub_group ()); 985if (sub == 0 ) { 986const float a = 987m_old == - INFINITY ?0.0f : sycl::exp2 (m_old - m_new ); 988S .alpha [r ]= a ; 989S .lsum [r ]= sycl::fma (S .lsum [r ], (float )a ,sum ); 990S .mrow [r ]= m_new ; 991 } 992 } 993/* 994DPCT1118: SYCL group functions and algorithms must be encountered in 995converged control flow. You may need to adjust the code. 996*/ 997/* 998DPCT1065: Consider replacing sycl::nd_item::barrier() with 999sycl::nd_item::barrier(sycl::access::fence_space::local_space) for 1000better performance if there is no access to global memory. 1001*/ 1002item_ct1 .barrier (); 1003// p.v over this warp's 64 dims (as v1) 1004 { 1005float vmax = S .sc [st ][warp ][1 ][lane ]; 1006#pragma unroll 1007/* 1008DPCT1108: '__shfl_xor_sync' was migrated with the experimental 1009feature masked sub_group function which may not be supported by all 1010compilers or runtimes. You may need to adjust the code. 1011*/ 1012for (int o = 16 ;o > 0 ;o >>=1 )vmax = sycl::fmax ( 1013vmax , dpct::experimental::permute_sub_group_by_xor ( 10140xffffffffu , 1015 sycl::ext::oneapi::this_work_item::get_sub_group (), 1016vmax ,o )); 1017const float vup = vmax > 0.0f ?16384.0f /vmax :0.0f ,vdown = vmax * (1.0f /16384.0f ); 1018float tmp [8 ][4 ]; 1019#pragma unroll 1020for (int j = 0 ;j < 8 ;++ j )tmp [j ][0 ]= tmp [j ][1 ]= tmp [j ][2 ]= tmp [j ][3 ]= 0.0f ; 1021#pragma unroll 1022for (int ks = 0 ;ks < CH2 /16 ;++ ks ) { 1023const int cA = ks * 16 + 2 * tig ,cB = cA + 8 ; 1024const float w0 = S .sc [st ][warp ][1 ][cA ]* vup ,w1 = S .sc [st ][warp ][1 ][cA + 1 ]* vup , 1025w2 = S .sc [st ][warp ][1 ][cB ]* vup ,w3 = S .sc [st ][warp ][1 ][cB + 1 ]* vup ; 1026const float p00 = S .p [gid ][cA ]* w0 ,p01 = S .p [gid ][cA + 1 ]* w1 ; 1027const float p10 = S .p [gid + 8 ][cA ]* w0 ,p11 = S .p [gid + 8 ][cA + 1 ]* w1 ; 1028const float p02 = S .p [gid ][cB ]* w2 ,p03 = S .p [gid ][cB + 1 ]* w3 ; 1029const float p12 = S .p [gid + 8 ][cB ]* w2 ,p13 = S .p [gid + 8 ][cB + 1 ]* w3 ; 1030uint32_t ah [4 ],al [4 ]; 1031ah [0 ]= pack_h2 (p00 ,p01 ); 1032ah [1 ]= pack_h2 (p10 ,p11 ); 1033ah [2 ]= pack_h2 (p02 ,p03 ); 1034ah [3 ]= pack_h2 (p12 ,p13 ); 1035 { 1036const sycl::half2 * h = 1037reinterpret_cast < const sycl::half2 *> (ah ); 1038 sycl::float2 f ; 1039f = h [0 ].template convert < float , 1040 sycl::rounding_mode::automatic > (); 1041al [0 ]= pack_h2 (p00 - f .x (),p01 - f .y ()); 1042f = h [1 ].template convert < float , 1043 sycl::rounding_mode::automatic > (); 1044al [1 ]= pack_h2 (p10 - f .x (),p11 - f .y ()); 1045f = h [2 ].template convert < float , 1046 sycl::rounding_mode::automatic > (); 1047al [2 ]= pack_h2 (p02 - f .x (),p03 - f .y ()); 1048f = h [3 ].template convert < float , 1049 sycl::rounding_mode::automatic > (); 1050al [3 ]= pack_h2 (p12 - f .x (),p13 - f .y ()); 1051 } 1052#pragma unroll 1053for (int j = 0 ;j < 8 ;++ j ) { 1054const int d = j * 8 + gid ; 1055const uint32_t x0 = (uint8_t )V [swz (cA ,d )] | ((uint32_t ) (uint8_t )V [swz (cA + 1 ,d )] <<8 ); 1056const uint32_t x1 = (uint8_t )V [swz (cB ,d )] | ((uint32_t ) (uint8_t )V [swz (cB + 1 ,d )] <<8 ); 1057uint32_t b [2 ]; 1058b [0 ]= i8x2_to_h2 (x0 ); 1059b [1 ]= i8x2_to_h2 (x1 ); 1060mma16816 (tmp [j ],ah ,b ); 1061mma16816 (tmp [j ],al ,b ); 1062 } 1063 } 1064const float a0 = S .alpha [gid ],a1 = S .alpha [gid + 8 ]; 1065#pragma unroll 1066for (int j = 0 ;j < 8 ;++ j ) { 1067acc [j ][0 ]= sycl::fma (acc [j ][0 ], (float )a0 ,tmp [j ][0 ]* vdown ); 1068acc [j ][1 ]= sycl::fma (acc [j ][1 ], (float )a0 ,tmp [j ][1 ]* vdown ); 1069acc [j ][2 ]= sycl::fma (acc [j ][2 ], (float )a1 ,tmp [j ][2 ]* vdown ); 1070acc [j ][3 ]= sycl::fma (acc [j ][3 ], (float )a1 ,tmp [j ][3 ]* vdown ); 1071 } 1072 } 1073if (more ) { 1074S .sc [st ^1 ][warp ][0 ][lane ]= ksn ; 1075S .sc [st ^1 ][warp ][1 ][lane ]= vsn ; 1076 } 1077 sycl::group_barrier (sycl::ext::oneapi::this_work_item::get_sub_group ()); 1078 } 1079/* 1080DPCT1065: Consider replacing sycl::nd_item::barrier() with 1081sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better 1082performance if there is no access to global memory. 1083*/ 1084item_ct1 .barrier (); 1085const float l0 = S .lsum [gid ],l1 = S .lsum [gid + 8 ]; 1086const float i0 = l0 > 0.0f ?1.0f /l0 :0.0f ,i1 = l1 > 0.0f ?1.0f /l1 :0.0f ; 1087#pragma unroll 1088for (int j = 0 ;j < 8 ;++ j ) { 1089const int d = dim0 + j * 8 + 2 * tig ; 1090* reinterpret_cast < sycl::float2 *> (attn + (size_t )gid * HD + d )= 1091 sycl::float2 (acc [j ][0 ]* i0 ,acc [j ][1 ]* i0 ); 1092if (gid + 8 < G ) 1093* reinterpret_cast < sycl::float2 *> (attn + (size_t )(gid + 8 )* HD + 1094d )= 1095 sycl::float2 (acc [j ][2 ]* i1 ,acc [j ][3 ]* i1 ); 1096 } 1097} 1098 1099bool launch_i8 (const float * q ,const QsaAttnPools & pools ,const int32_t * ids , 1100const int32_t * steps ,int64_t cap ,const QsaShapes & s , 1101float * attn ,int64_t n_q , dpct::queue_ptr st )try { 1102static bool attr [64 ]= {};// the shared-memory opt-in is per device (a layer split runs this on several) 1103int dev = 0 ; 1104dev = dpct::get_current_device_id (); 1105/* 1106DPCT1083: The size of local memory in the migrated code may be different 1107from the original code. Check that the allocated memory size in the migrated 1108code is correct. 1109*/ 1110const int bytes = (int )sizeof (Smem2 ); 1111if (dev < 0 || dev >=64 )return false; 1112if (!attr [dev ]) { 1113/* 1114DPCT1027: The call to cudaFuncSetAttribute was replaced with 0 1115because SYCL currently does not support corresponding setting. 1116*/ 1117if (0 != 0 ) { 1118/* 1119DPCT1026: The call to cudaGetLastError was removed because this 1120functionality is redundant in SYCL. 1121*/ 1122return false; 1123 } 1124attr [dev ]= true; 1125 } 1126const float scale_log2 = 1.4426950408889634f /sqrtf ((float )HD ); 1127for (int64_t q0 = 0 ;q0 < n_q ;q0 += 65535 ) { 1128const int64_t nb = n_q - q0 < 65535 ?n_q - q0 :65535 ; 1129 { 1130auto exp_props = sycl::ext::oneapi::experimental::properties { 1131 sycl::ext::oneapi::experimental::use_root_sync }; 1132 dpct::has_capability_or_fail (st -> get_device (), 1133 {sycl::aspect::fp16 }); 1134 1135 strata::kprof::kp (st ,__FILE__ ,__func__ ,__LINE__ )-> submit ([& ](sycl::handler & cgh ) { 1136 sycl::local_accessor < uint8_t ,1 > dpct_local_acc_ct1 ( 1137 sycl::range (bytes ),cgh ); 1138 1139auto q_q0_s_n_head_HD_ct0 = q + q0 * s .n_head * HD ; 1140auto ids_q0_cap_ct2 = ids + q0 * cap ; 1141auto steps_q0_kStepCount_ct3 = steps + q0 * kStepCount ; 1142auto attn_q0_s_n_head_HD_ct7 = attn + q0 * s .n_head * HD ; 1143 1144cgh .parallel_for < 1145dpct_kernel_name < class prompt_attn_i8_kernel_c3d463 >> ( 1146 sycl::nd_range < 3 > ( 1147 sycl::range (1 , (unsigned )s .n_head_kv , (unsigned )nb )* 1148 sycl::range (1 ,1 ,THREADS ), 1149 sycl::range (1 ,1 ,THREADS )), 1150exp_props , 1151 [= ](sycl::nd_item < 3 > item_ct1 ) [[sycl ::reqd_sub_group_size ( 115232 )]] { 1153prompt_attn_i8_kernel ( 1154q_q0_s_n_head_HD_ct0 ,pools ,ids_q0_cap_ct2 , 1155steps_q0_kStepCount_ct3 , (int )s .n_head_kv , 1156 (int )s .page_size ,scale_log2 , 1157attn_q0_s_n_head_HD_ct7 , (int )cap , 1158dpct_local_acc_ct1 1159 .get_multi_ptr < sycl::access::decorated::no > () 1160 .get ()); 1161 }); 1162 }); 1163 } 1164 } 1165/* 1166DPCT1010: SYCL uses exceptions to report errors and does not use the 1167error codes. The cudaGetLastError function call was replaced with 0. You 1168need to rewrite this code. 1169*/ 1170const dpct::err0 e = 0 ; 1171 1172return true; 1173} 1174catch (sycl::exception const & exc ) { 1175 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 1176 <<", line:" <<__LINE__ << std::endl ; 1177 std::exit (1 ); 1178} 1179 1180template < int KV_MODE > 1181bool launch (const float * q ,const QsaAttnPools & pools ,const int32_t * ids , 1182const int32_t * steps ,int64_t cap ,const QsaShapes & s ,float * attn , 1183int64_t n_q , dpct::queue_ptr st )try { 1184static bool attr [64 ]= {};// per device, as above 1185int dev = 0 ; 1186dev = dpct::get_current_device_id (); 1187/* 1188DPCT1083: The size of local memory in the migrated code may be different 1189from the original code. Check that the allocated memory size in the migrated 1190code is correct. 1191*/ 1192const int bytes = (int )sizeof (Smem < KV_MODE > ); 1193if (dev < 0 || dev >=64 )return false; 1194if (!attr [dev ]) { 1195/* 1196DPCT1027: The call to cudaFuncSetAttribute was replaced with 0 1197because SYCL currently does not support corresponding setting. 1198*/ 1199if (0 != 0 ) { 1200/* 1201DPCT1026: The call to cudaGetLastError was removed because this 1202functionality is redundant in SYCL. 1203*/ 1204return false; 1205 } 1206attr [dev ]= true; 1207 } 1208const float scale_log2 = 1.4426950408889634f /sqrtf ((float )HD ); 1209for (int64_t q0 = 0 ;q0 < n_q ;q0 += 65535 ) { 1210const int64_t nb = n_q - q0 < 65535 ?n_q - q0 :65535 ; 1211 { 1212auto exp_props = sycl::ext::oneapi::experimental::properties { 1213 sycl::ext::oneapi::experimental::use_root_sync }; 1214 dpct::has_capability_or_fail (st -> get_device (), 1215 {sycl::aspect::fp16 }); 1216 1217 strata::kprof::kp (st ,__FILE__ ,__func__ ,__LINE__ )-> submit ([& ](sycl::handler & cgh ) { 1218 sycl::local_accessor < uint8_t ,1 > dpct_local_acc_ct1 ( 1219 sycl::range (bytes ),cgh ); 1220 1221auto q_q0_s_n_head_HD_ct0 = q + q0 * s .n_head * HD ; 1222auto ids_q0_cap_ct2 = ids + q0 * cap ; 1223auto steps_q0_kStepCount_ct3 = steps + q0 * kStepCount ; 1224auto attn_q0_s_n_head_HD_ct7 = attn + q0 * s .n_head * HD ; 1225 1226cgh .parallel_for < 1227dpct_kernel_name < class prompt_attn_kernel_e09b15 , 1228dpct_kernel_scalar < KV_MODE >>> ( 1229 sycl::nd_range < 3 > ( 1230 sycl::range (1 , (unsigned )s .n_head_kv , (unsigned )nb )* 1231 sycl::range (1 ,1 ,THREADS ), 1232 sycl::range (1 ,1 ,THREADS )), 1233exp_props , 1234 [= ](sycl::nd_item < 3 > item_ct1 ) [[sycl ::reqd_sub_group_size ( 123532 )]] { 1236prompt_attn_kernel < KV_MODE > ( 1237q_q0_s_n_head_HD_ct0 ,pools ,ids_q0_cap_ct2 , 1238steps_q0_kStepCount_ct3 , (int )s .n_head_kv , 1239 (int )s .page_size ,scale_log2 , 1240attn_q0_s_n_head_HD_ct7 , (int )cap , 1241dpct_local_acc_ct1 1242 .get_multi_ptr < sycl::access::decorated::no > () 1243 .get ()); 1244 }); 1245 }); 1246 } 1247 } 1248/* 1249DPCT1010: SYCL uses exceptions to report errors and does not use the 1250error codes. The cudaGetLastError function call was replaced with 0. You 1251need to rewrite this code. 1252*/ 1253const dpct::err0 e = 0 ; 1254 1255return true; 1256} 1257catch (sycl::exception const & exc ) { 1258 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 1259 <<", line:" <<__LINE__ << std::endl ; 1260 std::exit (1 ); 1261} 1262 1263// PR #600: compiled only into the experimental build (-DSTRATA_EXPERIMENTAL_SM60=ON), the one build that runs on a 1264// Volta card; the ready-made engine has none of it (no extra kernels to load, the same code as before). 1265#if !defined(__HIPCC__ )&& defined(STRATA_EXPERIMENTAL_SM60 ) 1266// ---- sm_70 (Volta): v1's structure on mma.m8n8k4 ------------------------------------------------------------------ 1267// Volta's tensor cores only have m8n8k4 (FP16 in, FP32 accumulate): per warp FOUR independent 8x8x4 products, one per 1268// quad-pair (QP q = lanes 4q..4q+3 and 4q+16..4q+19; thread j = (lane & 3) + 4 * (lane >> 4) within it). Layout, measured on 1269// a V100 (tools-free microtest, and equal to turbomind's SM70_MMA_884): the thread holds row j of A (k 0..3 as two 1270// registers) and column j of B (k 0..3); C register i is row (lane & 1) + 4 * (lane >> 4) + 2 * ((i >> 1) & 1), 1271// column (lane & 2) + 4 * (i >> 2) + (i & 1) of its QP's 8x8 tile. 1272// q.k: warp w owns dims [64w, 64w+64) = int8 scale group w; QP q takes cells 8q..8q+7 of the 32-cell chunk; 16 k-steps 1273// of 4 dims, two 8-row blocks (12 heads + 4 zero rows), q as hi + lo halves. The warp's partial (times the 1274// cells' K scale) goes to S.part[w]; the softmax adds the four groups in a fixed order (deterministic). 1275// p.v: warp w owns dims [64w, 64w+64) again; QP q takes the 16 dims 64w+16q.. (two n-tiles of 8); k = the 32 cells in 1276// steps of 4; p carries the V scale (as v1) and is split into hi + lo halves. 1277#if defined(__CUDA_ARCH__ )&& __CUDA_ARCH__ >=700 && __CUDA_ARCH__ < 750 1278#define STRATA_PA_VOLTA 1 1279#else 1280#define STRATA_PA_VOLTA 0 1281#endif 1282 1283__device__ __forceinline__ void mma884 (float * c ,uint32_t a0 ,uint32_t a1 ,uint32_t b0 ,uint32_t b1 ) { 1284#if STRATA_PA_VOLTA 1285 asmvolatile ("mma.sync.aligned.m8n8k4.row.col.f32.f16.f16.f32 {%0,%1,%2,%3,%4,%5,%6,%7}, {%8,%9}, {%10,%11}, " 1286"{%0,%1,%2,%3,%4,%5,%6,%7};\n" 1287 :"+f" (c [0 ]),"+f" (c [1 ]),"+f" (c [2 ]),"+f" (c [3 ]),"+f" (c [4 ]),"+f" (c [5 ]),"+f" (c [6 ]),"+f" (c [7 ]) 1288 :"r" (a0 ),"r" (a1 ),"r" (b0 ),"r" (b1 )); 1289#else 1290/* unreachable on SYCL: the launcher refuses this device */ // m8n8k4 is a Volta instruction; the host only launches this kernel on sm_70 1291#endif 1292} 1293 1294template < int KV_MODE > 1295struct Smem70 { 1296using KElem = typename std::conditional < KV_MODE == 0 ,__half ,int8_t > ::type ; 1297using VElem = typename std::conditional < KV_MODE == 1 ,int8_t ,__half > ::type ; 1298static constexpr int KROW = KV_MODE == 0 ?HD + 8 :HD + 16 ; 1299static constexpr int VROW = KV_MODE == 1 ?HD + 16 :HD + 8 ; 1300__half qh [16 ][QS ]; 1301__half ql [16 ][QS ]; 1302KElem k [CH ][KROW ]; 1303VElem v [CH ][VROW ]; 1304float ks [CH ][4 ]; 1305float vs [CH ][4 ]; 1306float part [4 ][16 ][CH + 4 ];// q.k per dim group (scaled by the cell's K scale) 1307float s [16 ][CH + 4 ];// the chunk's probabilities 1308float qmax [THREADS /32 ]; 1309float alpha [16 ]; 1310float lsum [16 ]; 1311float mrow [16 ]; 1312long long row [CH ]; 1313}; 1314 1315template < int KV_MODE > 1316__global__ void __launch_bounds__ (THREADS )prompt_attn_v70_kernel (const float * __restrict__q ,QsaAttnPools p , 1317const int32_t * __restrict__ids , 1318const int32_t * __restrict__steps ,int n_kv_heads , 1319int page_size ,float scale_log2 , 1320float * __restrict__attn ,int cap ) { 1321extern __shared__ __align__ (16 )unsigned char smem_raw []; 1322Smem70 < KV_MODE >& S = * reinterpret_cast < Smem70 < KV_MODE >*> (smem_raw ); 1323const int qi = blockIdx .x ,kvh = blockIdx .y ; 1324const int n_head = n_kv_heads * G ; 1325q += (size_t )qi * n_head * HD + (size_t )kvh * G * HD ; 1326attn += (size_t )qi * n_head * HD + (size_t )kvh * G * HD ; 1327ids += (size_t )qi * cap ; 1328const int n = __ldg (steps + (size_t )qi * kStepCount + kStepWidth ); 1329const int t = threadIdx .x ,lane = t & 31 ,warp = t >>5 ; 1330const int qp = (lane >>2 )& 3 ,jj = (lane & 3 )+ 4 * (lane >>4 );// quad-pair, thread within it 1331const int crow = (lane & 1 )+ 4 * (lane >>4 );// C row of register 0 (+2 per register pair) 1332const int ccol = lane & 2 ;// C column of register 0 (+4 per half, +1 per reg) 1333 1334// q: 12 heads + 4 zero rows, scaled by a power of two that puts its largest value near 2^14 (exact, and the 1335// lo halves stay out of FP16's subnormal range), then split into hi + lo halves 1336float qm = 0.0f ; 1337for (int i = t ;i < G * HD ;i += THREADS )qm = fmaxf (qm ,fabsf (q [i ])); 1338#pragma unroll 1339for (int o = 16 ;o > 0 ;o >>=1 )qm = fmaxf (qm ,__shfl_xor_sync (0xffffffffu ,qm ,o )); 1340if (lane == 0 )S .qmax [warp ]= qm ; 1341__syncthreads (); 1342qm = fmaxf (fmaxf (S .qmax [0 ],S .qmax [1 ]),fmaxf (S .qmax [2 ],S .qmax [3 ])); 1343int qe = 0 ; 1344if (qm > 0.0f )frexpf (qm ,& qe );// qm < 2^qe 1345const float qup = ldexpf (1.0f ,14 - qe ),qdown = ldexpf (scale_log2 ,qe - 14 ); 1346for (int i = t ;i < 16 * HD ;i += THREADS ) { 1347const int h = i /HD ,d = i %HD ; 1348const float x = h < G ?q [(size_t )h * HD + d ]* qup :0.0f ; 1349const __half hi = __float2half_rn (x ); 1350S .qh [h ][d ]= hi ; 1351S .ql [h ][d ]= __float2half_rn (x - __half2float (hi )); 1352 } 1353if (t < 16 ) {S .mrow [t ]= - INFINITY ;S .lsum [t ]= 0.0f ; } 1354 1355float acc [2 ][2 ][8 ]; 1356#pragma unroll 1357for (int rb = 0 ;rb < 2 ;++ rb ) 1358#pragma unroll 1359for (int nt = 0 ;nt < 2 ;++ nt ) 1360#pragma unroll 1361for (int i = 0 ;i < 8 ;++ i )acc [rb ][nt ][i ]= 0.0f ; 1362 1363for (int c0 = 0 ;c0 < n ;c0 += CH ) { 1364const int nh = min (CH ,n - c0 ); 1365if (t < CH ) { 1366long long r = -1 ; 1367if (t < nh ) { 1368const int cell = ids [c0 + t ]; 1369const long long page = (long long )p .page_table [cell /page_size ]; 1370r = (page * n_kv_heads + kvh )* page_size + (cell %page_size ); 1371 } 1372S .row [t ]= r ; 1373 } 1374__syncthreads ();// rows ready; the previous chunk's p.v is done with k, v, s 1375// gather the chunk's K and V rows (16-byte pieces; K8V4's V as q4_0 blocks dequantized to fp16) 1376// and their scales 1377 { 1378constexpr int KPIECES = HD * (int )sizeof (typename Smem < KV_MODE > ::KElem ) /16 ;// per K row 1379for (int i = t ;i < CH * KPIECES ;i += THREADS ) { 1380const int c = i /KPIECES ,pc = i %KPIECES ; 1381const long long r = S .row [c ]; 1382uint4 kx = make_uint4 (0 ,0 ,0 ,0 ); 1383if (r >=0 ) { 1384if constexpr (KV_MODE == 0 ) 1385kx = __ldg (reinterpret_cast < const uint4 *> (p .k_pool + r * HD )+ pc ); 1386else // modes 1 and 3: the K side is INT8 1387kx = __ldg (reinterpret_cast < const uint4 *> (p .k_q + r * HD )+ pc ); 1388 } 1389* reinterpret_cast < uint4 *> (reinterpret_cast < unsigned char *> (& S .k [c ][0 ])+ pc * 16 )= kx ; 1390 } 1391if constexpr (KV_MODE == 3 ) {// V: dequantize the row's q4_0 blocks straight into the fp16 V row 1392constexpr int BLKS = HD /QK4_0 ; 1393constexpr int BYTES = BLKS * (int )sizeof (block_q4_0 ); 1394for (int i = t ;i < CH * BLKS ;i += THREADS ) { 1395const int c = i /BLKS ,b = i %BLKS ; 1396const long long r = S .row [c ]; 1397#pragma unroll 1398for (int j = 0 ;j < QK4_0 ;++ j )S .v [c ][b * QK4_0 + j ]= __half (0 ); 1399if (r >=0 ) { 1400const block_q4_0 * blk = reinterpret_cast < const block_q4_0 *> (p .v_q4 + r * BYTES )+ b ; 1401const float d = __half2float (__ushort_as_half (blk -> d )); 1402#pragma unroll 1403for (int j = 0 ;j < QK4_0 /2 ;++ j ) { 1404S .v [c ][b * QK4_0 + j ]= __float2half_rn ((float ) ((int )(blk -> qs [j ]& 0x0F )- 8 )* d ); 1405S .v [c ][b * QK4_0 + j + QK4_0 /2 ]= 1406__float2half_rn ((float ) ((int )(blk -> qs [j ] >>4 )- 8 )* d ); 1407 } 1408 } 1409 } 1410 }else { 1411constexpr int VPIECES = HD * (int )sizeof (typename Smem < KV_MODE > ::VElem ) /16 ;// per V row 1412for (int i = t ;i < CH * VPIECES ;i += THREADS ) { 1413const int c = i /VPIECES ,pc = i %VPIECES ; 1414const long long r = S .row [c ]; 1415uint4 vx = make_uint4 (0 ,0 ,0 ,0 ); 1416if (r >=0 ) { 1417if constexpr (KV_MODE == 1 ) 1418vx = __ldg (reinterpret_cast < const uint4 *> (p .v_q + r * HD )+ pc ); 1419else 1420vx = __ldg (reinterpret_cast < const uint4 *> (p .v_pool + r * HD )+ pc ); 1421 } 1422* reinterpret_cast < uint4 *> (reinterpret_cast < unsigned char *> (& S .v [c ][0 ])+ pc * 16 )= vx ; 1423 } 1424 } 1425for (int i = t ;i < CH * 4 ;i += THREADS ) { 1426const int c = i /4 ,g = i %4 ; 1427const long long r = S .row [c ]; 1428float a = 0.0f ,b = 0.0f ; 1429if (r >=0 ) { 1430if constexpr (KV_MODE == 1 ) { 1431a = __half2float (__ushort_as_half (p .k_scale [r * (HD /KV_Q8_GROUP )+ g ])); 1432b = __half2float (__ushort_as_half (p .v_scale [r * (HD /KV_Q8_GROUP )+ g ])); 1433 }else if constexpr (KV_MODE == 3 ) {// K as int8, V dequantized to fp16 (scale 1) 1434a = __half2float (__ushort_as_half (p .k_scale [r * (HD /KV_Q8_GROUP )+ g ])); 1435b = 1.0f ; 1436 }else { 1437a = b = 1.0f ; 1438 } 1439 } 1440S .ks [c ][g ]= a ; 1441S .vs [c ][g ]= b ; 1442 } 1443 } 1444__syncthreads (); 1445// scores: warp w = dim group w (64 dims), QP q = cells 8q..8q+7 1446 { 1447float tg [2 ][8 ]; 1448#pragma unroll 1449for (int rb = 0 ;rb < 2 ;++ rb ) 1450#pragma unroll 1451for (int i = 0 ;i < 8 ;++ i )tg [rb ][i ]= 0.0f ; 1452const int cell_b = qp * 8 + jj ; 1453#pragma unroll 1454for (int ks = 0 ;ks < 16 ;++ ks ) { 1455const int d0 = warp * 64 + ks * 4 ; 1456uint32_t b0 ,b1 ; 1457if constexpr (KV_MODE != 0 ) {// modes 1 and 3: the K side is INT8 codes, exact in FP16 1458const uint32_t raw = * reinterpret_cast < const uint32_t *> (& S .k [cell_b ][d0 ]); 1459b0 = i8x2_to_h2 (raw & 0xffffu ); 1460b1 = i8x2_to_h2 (raw >>16 ); 1461 }else { 1462const uint2 raw = * reinterpret_cast < const uint2 *> (& S .k [cell_b ][d0 ]); 1463b0 = raw .x ; 1464b1 = raw .y ; 1465 } 1466#pragma unroll 1467for (int rb = 0 ;rb < 2 ;++ rb ) { 1468const uint2 ah = * reinterpret_cast < const uint2 *> (& S .qh [rb * 8 + jj ][d0 ]); 1469const uint2 al = * reinterpret_cast < const uint2 *> (& S .ql [rb * 8 + jj ][d0 ]); 1470mma884 (tg [rb ],ah .x ,ah .y ,b0 ,b1 ); 1471mma884 (tg [rb ],al .x ,al .y ,b0 ,b1 ); 1472 } 1473 } 1474#pragma unroll 1475for (int rb = 0 ;rb < 2 ;++ rb ) 1476#pragma unroll 1477for (int i = 0 ;i < 8 ;++ i ) { 1478const int row = rb * 8 + crow + 2 * ((i >>1 )& 1 ); 1479const int cell = qp * 8 + ccol + 4 * (i >>2 )+ (i & 1 ); 1480S .part [warp ][row ][cell ]= tg [rb ][i ]* S .ks [cell ][warp ]; 1481 } 1482 } 1483__syncthreads (); 1484// online softmax: row t/8, 4 cells per thread, 8 threads per row (lanes 8r..8r+7 of a warp) 1485 { 1486constexpr int PER = CH /8 ; 1487const int r = t >>3 ,sub = t & 7 ; 1488float x [PER ],mx = - INFINITY ; 1489#pragma unroll 1490for (int j = 0 ;j < PER ;++ j ) { 1491const int c = sub * PER + j ; 1492const float sum4 = ((S .part [0 ][r ][c ]+ S .part [1 ][r ][c ])+ S .part [2 ][r ][c ])+ S .part [3 ][r ][c ]; 1493x [j ]= c < nh ?sum4 * qdown :- INFINITY ; 1494mx = fmaxf (mx ,x [j ]); 1495 } 1496#pragma unroll 1497for (int o = 1 ;o < 8 ;o <<=1 )mx = fmaxf (mx ,__shfl_xor_sync (0xffffffffu ,mx ,o )); 1498const float m_old = S .mrow [r ]; 1499const float m_new = fmaxf (m_old ,mx ); 1500float sum = 0.0f ; 1501#pragma unroll 1502for (int j = 0 ;j < PER ;++ j ) { 1503const float e = x [j ]== - INFINITY ?0.0f :exp2f (x [j ]- m_new ); 1504S .s [r ][sub * PER + j ]= e ; 1505sum += e ; 1506 } 1507#pragma unroll 1508for (int o = 1 ;o < 8 ;o <<=1 )sum += __shfl_xor_sync (0xffffffffu ,sum ,o ); 1509__syncwarp (); 1510if (sub == 0 ) { 1511const float a = m_old == - INFINITY ?0.0f :exp2f (m_old - m_new ); 1512S .alpha [r ]= a ; 1513S .lsum [r ]= fmaf (S .lsum [r ],a ,sum ); 1514S .mrow [r ]= m_new ; 1515 } 1516 } 1517__syncthreads (); 1518__syncthreads (); 1519// p.v: warp w owns dims [64w, 64w+64) (int8 scale group w), QP q its 16 dims 64w+16q..; the V scale is folded 1520// into p relative to the chunk's largest, times 2^14 (as v1) 1521 { 1522float vmax = 0.0f ; 1523#pragma unroll 1524for (int c = lane ;c < CH ;c += 32 )vmax = fmaxf (vmax ,S .vs [c ][warp ]); 1525#pragma unroll 1526for (int o = 16 ;o > 0 ;o >>=1 )vmax = fmaxf (vmax ,__shfl_xor_sync (0xffffffffu ,vmax ,o )); 1527const float vup = vmax > 0.0f ?16384.0f /vmax :0.0f ,vdown = vmax * (1.0f /16384.0f ); 1528float tmp [2 ][2 ][8 ]; 1529#pragma unroll 1530for (int rb = 0 ;rb < 2 ;++ rb ) 1531#pragma unroll 1532for (int nt = 0 ;nt < 2 ;++ nt ) 1533#pragma unroll 1534for (int i = 0 ;i < 8 ;++ i )tmp [rb ][nt ][i ]= 0.0f ; 1535#pragma unroll 1536for (int ks = 0 ;ks < CH /4 ;++ ks ) { 1537const int c0 = ks * 4 ; 1538float w [4 ]; 1539#pragma unroll 1540for (int e = 0 ;e < 4 ;++ e )w [e ]= S .vs [c0 + e ][warp ]* vup ; 1541uint2 ah [2 ],al [2 ]; 1542#pragma unroll 1543for (int rb = 0 ;rb < 2 ;++ rb ) { 1544const float4 pv = * reinterpret_cast < const float4 *> (& S .s [rb * 8 + jj ][c0 ]); 1545const float p0 = pv .x * w [0 ],p1 = pv .y * w [1 ],p2 = pv .z * w [2 ],p3 = pv .w * w [3 ]; 1546ah [rb ].x = pack_h2 (p0 ,p1 ); 1547ah [rb ].y = pack_h2 (p2 ,p3 ); 1548const float2 f01 = __half22float2 (* reinterpret_cast < const __half2 *> (& ah [rb ].x )); 1549const float2 f23 = __half22float2 (* reinterpret_cast < const __half2 *> (& ah [rb ].y )); 1550al [rb ].x = pack_h2 (p0 - f01 .x ,p1 - f01 .y ); 1551al [rb ].y = pack_h2 (p2 - f23 .x ,p3 - f23 .y ); 1552 } 1553#pragma unroll 1554for (int nt = 0 ;nt < 2 ;++ nt ) { 1555const int d = warp * 64 + qp * 16 + nt * 8 + jj ; 1556uint32_t b0 ,b1 ; 1557if constexpr (KV_MODE == 1 ) { 1558const uint32_t x0 = (uint8_t )S .v [c0 ][d ] | ((uint32_t ) (uint8_t )S .v [c0 + 1 ][d ] <<8 ); 1559const uint32_t x1 = (uint8_t )S .v [c0 + 2 ][d ] | ((uint32_t ) (uint8_t )S .v [c0 + 3 ][d ] <<8 ); 1560b0 = i8x2_to_h2 (x0 ); 1561b1 = i8x2_to_h2 (x1 ); 1562 }else { 1563const __half2 h0 = __halves2half2 (S .v [c0 ][d ],S .v [c0 + 1 ][d ]); 1564const __half2 h1 = __halves2half2 (S .v [c0 + 2 ][d ],S .v [c0 + 3 ][d ]); 1565b0 = * reinterpret_cast < const uint32_t *> (& h0 ); 1566b1 = * reinterpret_cast < const uint32_t *> (& h1 ); 1567 } 1568#pragma unroll 1569for (int rb = 0 ;rb < 2 ;++ rb ) { 1570mma884 (tmp [rb ][nt ],ah [rb ].x ,ah [rb ].y ,b0 ,b1 ); 1571mma884 (tmp [rb ][nt ],al [rb ].x ,al [rb ].y ,b0 ,b1 ); 1572 } 1573 } 1574 } 1575#pragma unroll 1576for (int rb = 0 ;rb < 2 ;++ rb ) { 1577float a_ [2 ]; 1578a_ [0 ]= S .alpha [rb * 8 + crow ]; 1579a_ [1 ]= S .alpha [rb * 8 + crow + 2 ]; 1580#pragma unroll 1581for (int nt = 0 ;nt < 2 ;++ nt ) 1582#pragma unroll 1583for (int i = 0 ;i < 8 ;++ i ) 1584acc [rb ][nt ][i ]= fmaf (acc [rb ][nt ][i ],a_ [(i >>1 )& 1 ],tmp [rb ][nt ][i ]* vdown ); 1585 } 1586 } 1587 } 1588__syncthreads (); 1589#pragma unroll 1590for (int rb = 0 ;rb < 2 ;++ rb ) 1591#pragma unroll 1592for (int h = 0 ;h < 2 ;++ h ) { 1593const int row = rb * 8 + crow + 2 * h ; 1594if (row >=G )continue ; 1595const float l = S .lsum [row ]; 1596const float inv = l > 0.0f ?1.0f /l :0.0f ; 1597#pragma unroll 1598for (int nt = 0 ;nt < 2 ;++ nt ) 1599#pragma unroll 1600for (int hh = 0 ;hh < 2 ;++ hh ) { 1601const int i = hh * 4 + h * 2 ;// registers i, i+1: row h, columns ccol + 4 * hh + {0, 1} 1602const int d = warp * 64 + qp * 16 + nt * 8 + ccol + 4 * hh ; 1603* reinterpret_cast < float2 *> (attn + (size_t )row * HD + d )= 1604make_float2 (acc [rb ][nt ][i ]* inv ,acc [rb ][nt ][i + 1 ]* inv ); 1605 } 1606 } 1607} 1608 1609template < int KV_MODE > 1610bool launch70 (const float * q ,const QsaAttnPools & pools ,const int32_t * ids ,const int32_t * steps ,int64_t cap , 1611const QsaShapes & s ,float * attn ,int64_t n_q ,cudaStream_t st ) { 1612static bool attr [64 ]= {}; 1613int dev = 0 ; 1614cudaGetDevice (& dev ); 1615const int bytes = (int )sizeof (Smem70 < KV_MODE > ); 1616if (dev < 0 || dev >=64 )return false; 1617if (!attr [dev ]) { 1618if (cudaFuncSetAttribute (prompt_attn_v70_kernel < KV_MODE > ,cudaFuncAttributeMaxDynamicSharedMemorySize ,bytes )!= 1619cudaSuccess ) { 1620cudaGetLastError (); 1621return false; 1622 } 1623attr [dev ]= true; 1624 } 1625const float scale_log2 = 1.4426950408889634f /sqrtf ((float )HD ); 1626for (int64_t q0 = 0 ;q0 < n_q ;q0 += 65535 ) { 1627const int64_t nb = n_q - q0 < 65535 ?n_q - q0 :65535 ; 1628prompt_attn_v70_kernel < KV_MODE > <<<dim3(( unsigned ) nb , ( unsigned ) s . n_head_kv ), THREADS , bytes , st > >>( 1629q + q0 * s . n_head * HD , pools , ids + q0 * cap , steps + q0 * kStepCount , ( int ) s . n_head_kv , 1630( int ) s . page_size , scale_log2 , attn + q0 * s . n_head * HD , ( int ) cap ); 1631} 1632const cudaError_t e = cudaGetLastError(); 1633if ( e != cudaSuccess ) { 1634std::fprintf( stderr , "qsa_prompt_attn_batch (sm_70): %s\n" , cudaGetErrorString( e )); 1635std::exit( 1 ); 1636} 1637return true; 1638} 1639#else // AMD, or a build without STRATA_EXPERIMENTAL_SM60: no m8n8k4 kernel (the caller keeps the old one) 1640template < int KV_MODE > 1641bool launch70( const float * , const QsaAttnPools & , const int32_t * , 1642const int32_t * , int64_t , const QsaShapes & , float * , int64_t , 1643dpct:: queue_ptr ) { 1644return false; 1645} 1646#endif // !__HIPCC__ && STRATA_EXPERIMENTAL_SM60 1647 1648#if defined( __HIPCC__ ) 1649// ---- S6: the int8-KV prompt attention on RDNA4 matrix cores (opt-in: STRATA_HIP_WMMA=1, gfx12 only). The design of 1650// the v2 kernel above with gfx12's v_wmma_f32_16x16x16_f16 (wave32) in place of m16n8k16: wave w owns dims 1651// [64w, 64w+64) (int8 scale group w) for q.k and p.v; q and p are split into FP16 hi + lo parts, the int8 codes enter 1652// exactly as FP16, the scales are applied in FP32 and the four groups' q.k partials are added in a fixed order. 1653// FP32-level accuracy, deterministic, but not bitwise equal to qsa_decode_attn_batch (another summation order). 1654// Fragment layout (16x16x16, wave32, checked on gfx1201): A lane l holds A[l % 16][(l / 16) * 8 + i], B lane l holds 1655// B[(l / 16) * 8 + i][l % 16], C/D lane l holds D[(l / 16) * 8 + i][l % 16], i = 0..7. 1656// gfx11 (RDNA3 / RDNA3.5: gfx110x, gfx115x) has the same instruction with another layout: A lane l holds all 16 k of 1657// row l % 16 (lanes 16..31 repeat lanes 0..15), B lane l all 16 k of column l % 16, and C/D lane l holds 1658// D[2 * i + l / 16][l % 16]. PA_KL is the k values per lane (8 or 16), PA_KOFF(half) the first one, PA_ROW the C row. 1659#if defined( __gfx1200__ ) || defined( __gfx1201__ ) 1660#define STRATA_PA_WMMA 1 1661#define STRATA_PA_GFX11 0 1662#elif defined( __gfx1100__ ) || defined( __gfx1101__ ) || defined( __gfx1102__ ) || defined( __gfx1150__ ) || \ 1663defined( __gfx1151__ ) 1664#define STRATA_PA_WMMA 1 1665#define STRATA_PA_GFX11 1 1666#else 1667#define STRATA_PA_WMMA 0 1668#define STRATA_PA_GFX11 0 1669#endif 1670#if STRATA_PA_GFX11 1671constexpr int PA_KL = 16 ; 1672#define PA_KOFF( half ) 0 1673#define PA_ROW( i , half ) (2 * (i) + (half)) 1674#else 1675constexpr int PA_KL = 8 ; 1676#define PA_KOFF( half ) ((half) * 8) 1677#define PA_ROW( i , half ) ((half) * 8 + (i)) 1678#endif 1679typedef _Float16 wh8 __attribute__((ext_vector_type( PA_KL ))); 1680typedef float wf8 __attribute__((ext_vector_type( 8 ))); 1681constexpr int WCH = 32 ; // cells per chunk (two 16-cell tiles) 1682constexpr int WVS = 80 ; // staged V row stride in bytes (64 codes, 16-byte aligned, banks spread) 1683struct alignas( 16 ) SmemW { 1684float part [ 4 ][ 16 ][ WCH + 1 ]; // q.k per dim group 1685float p [ 16 ][ WCH + 1 ]; 1686float vs [ 4 ][ WCH ]; // V scale per (group, cell) 1687int valid [ WCH ]; // the cell has a resident pool row 1688uint8_t v [ 4 ][ WCH ][ WVS ]; // per wave: the chunk's V codes of its group, one row per cell 1689float qmax [ 4 ]; 1690float alpha [ 16 ]; 1691float lsum [ 16 ]; 1692float mrow [ 16 ]; 1693}; 1694 1695__device__ __forceinline__ wf8 wmma_f16( wh8 a , wh8 b , wf8 c ) { 1696#if STRATA_PA_WMMA && STRATA_PA_GFX11 1697return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32( a , b , c ); 1698#elif STRATA_PA_WMMA 1699return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12( a , b , c ); 1700#else 1701__builtin_trap(); 1702return c ; 1703#endif 1704} 1705 1706__device__ __forceinline__ wh8 i8_to_h( const uint32_t * x ) { // PA_KL codes, exact: |code| <= 128 1707wh8 h ; 1708#pragma unroll 1709for ( int i = 0 ; i < PA_KL ; ++ i ) h [ i ] = ( _Float16 ) ( int ) ( int8_t ) ( x [ i / 4 ] >> ( 8 * ( i % 4 ))); 1710return h ; 1711} 1712 1713// SPLIT = true (default): q and p carried as FP16 hi + lo pairs (two WMMAs each: FP32-level). S23 (opt-in 1714// STRATA_PA_FAST=1): SPLIT = false, one FP16 image each - half the matrix work, rounding-level (FP16 attention as the 1715// usual flash-attention kernels), quality-gated 1716template < bool SPLIT > 1717__global__ void __launch_bounds__ ( THREADS ) prompt_attn_wmma_kernel( const float * __restrict__ q , QsaAttnPools p , 1718const int32_t * __restrict__ ids , 1719const int32_t * __restrict__ steps , int n_kv_heads , 1720int page_size , float scale_log2 , 1721float * __restrict__ attn , int cap ) { 1722#if STRATA_PA_WMMA 1723__shared__ SmemW S ; 1724const int qi = blockIdx . x , kvh = blockIdx . y ; 1725const int n_head = n_kv_heads * G ; 1726q += ( size_t ) qi * n_head * HD + ( size_t ) kvh * G * HD ; 1727attn += ( size_t ) qi * n_head * HD + ( size_t ) kvh * G * HD ; 1728ids += ( size_t ) qi * cap ; 1729const int n = __ldg( steps + ( size_t ) qi * kStepCount + kStepWidth ); 1730const int t = threadIdx . x , lane = t & 31 , warp = t >> 5 ; 1731const int col = lane & 15 , half = lane >> 4 ; // fragment column / k half 1732const int dim0 = warp * 64 ; 1733 1734float qm = 0.0f ; 1735for ( int i = t ; i < G * HD ; i += THREADS ) qm = fmaxf( qm , fabsf( q [ i ])); 1736#pragma unroll 1737for ( int o = 16 ; o > 0 ; o >>= 1 ) qm = fmaxf( qm , __shfl_xor_sync( 0xffffffffu , qm , o )); 1738if ( lane == 0 ) S . qmax [ warp ] = qm ; 1739if ( t < 16 ) { S . mrow [ t ] = - INFINITY ; S . lsum [ t ] = 0.0f ; } 1740__syncthreads(); 1741qm = fmaxf(fmaxf( S . qmax [ 0 ], S . qmax [ 1 ]), fmaxf( S . qmax [ 2 ], S . qmax [ 3 ])); 1742int qe = 0 ; 1743if ( qm > 0.0f ) frexpf( qm , & qe ); 1744const float qup = ldexpf( 1.0f , 14 - qe ), qdown = ldexpf( scale_log2 , qe - 14 ); 1745// q A fragments of this wave's 64 dims: row = col (heads 12..15 zero), k = dim0 + kk*16 + PA_KOFF(half) + i 1746wh8 qh [ 4 ], ql [ 4 ]; 1747#pragma unroll 1748for ( int kk = 0 ; kk < 4 ; ++ kk ) { 1749float x [ PA_KL ]; 1750if ( col < G ) { 1751const float4 * src = reinterpret_cast < const float4 *> ( q + ( size_t ) col * HD + dim0 + kk * 16 + PA_KOFF( half )); 1752#pragma unroll 1753for ( int j = 0 ; j < PA_KL / 4 ; ++ j ) { 1754const float4 a = src [ j ]; 1755x [ 4 * j ] = a . x ; x [ 4 * j + 1 ] = a . y ; x [ 4 * j + 2 ] = a . z ; x [ 4 * j + 3 ] = a . w ; 1756} 1757} else { 1758#pragma unroll 1759for ( int i = 0 ; i < PA_KL ; ++ i ) x [ i ] = 0.0f ; 1760} 1761#pragma unroll 1762for ( int i = 0 ; i < PA_KL ; ++ i ) { 1763const float v = x [ i ] * qup ; 1764const _Float16 hi = ( _Float16 ) v ; 1765qh [ kk ][ i ] = hi ; 1766ql [ kk ][ i ] = ( _Float16 ) ( v - ( float ) hi ); 1767} 1768} 1769 1770wf8 acc [ 4 ]; 1771#pragma unroll 1772for ( int j = 0 ; j < 4 ; ++ j ) acc [ j ] = wf8 { 0.f , 0.f , 0.f , 0.f , 0.f , 0.f , 0.f , 0.f }; 1773 1774const int n_chunks = ( n + WCH - 1 ) / WCH ; 1775for ( int ci = 0 ; ci < n_chunks ; ++ ci ) { 1776const int c0 = ci * WCH ; 1777// this lane's cell of the chunk (lane = cell index): its pool row, or -1 (past the selection, or a block the 1778// KV streaming left non-resident: masked as in the decode kernel) 1779long long myrow = -1 ; 1780if ( c0 + lane < n ) { 1781const int cell = __ldg( ids + c0 + lane ); 1782const long long page = ( long long ) __ldg( p . page_table + cell / page_size ); 1783if ( page >= 0 ) myrow = ( page * n_kv_heads + kvh ) * page_size + ( cell % page_size ); 1784} 1785// stage this wave's V slice of the chunk (64 bytes of each row) and the V scale; the K fragments come straight 1786// from global memory (8 consecutive codes per lane) 1787{ 1788uint4 v0 = make_uint4( 0 , 0 , 0 , 0 ), v1 = v0 , v2 = v0 , v3 = v0 ; 1789float vsc = 0.0f ; 1790if ( myrow >= 0 ) { 1791const uint4 * src = reinterpret_cast < const uint4 *> ( p . v_q + myrow * HD + dim0 ); 1792v0 = __ldg( src ); v1 = __ldg( src + 1 ); v2 = __ldg( src + 2 ); v3 = __ldg( src + 3 ); 1793vsc = __half2float(__ushort_as_half(__ldg( p . v_scale + myrow * ( HD / KV_Q8_GROUP ) + warp ))); 1794} 1795uint4 * dst = reinterpret_cast < uint4 *> ( & S . v [ warp ][ lane ][ 0 ]); 1796dst [ 0 ] = v0 ; dst [ 1 ] = v1 ; dst [ 2 ] = v2 ; dst [ 3 ] = v3 ; 1797S . vs [ warp ][ lane ] = vsc ; 1798if ( warp == 0 ) S . valid [ lane ] = myrow >= 0 ; 1799} 1800// q.k over this wave's 64 dims for two 16-cell tiles, times the cell's K scale for this group 1801#pragma unroll 1802for ( int nt = 0 ; nt < 2 ; ++ nt ) { 1803const long long rr = __shfl( myrow , nt * 16 + col ); 1804wf8 s = wf8 { 0.f , 0.f , 0.f , 0.f , 0.f , 0.f , 0.f , 0.f }; 1805float ksc = 0.0f ; 1806if ( rr >= 0 ) ksc = __half2float(__ushort_as_half(__ldg( p . k_scale + rr * ( HD / KV_Q8_GROUP ) + warp ))); 1807#pragma unroll 1808for ( int kk = 0 ; kk < 4 ; ++ kk ) { 1809uint32_t kx [ PA_KL / 4 ] = {}; 1810if ( rr >= 0 ) { 1811const uint32_t * src = reinterpret_cast < const uint32_t *> ( p . k_q + rr * HD + dim0 + kk * 16 + PA_KOFF( half )); 1812#if STRATA_PA_GFX11 1813const uint4 v = __ldg(reinterpret_cast < const uint4 *> ( src )); 1814kx [ 0 ] = v . x ; kx [ 1 ] = v . y ; kx [ 2 ] = v . z ; kx [ 3 ] = v . w ; 1815#else 1816const uint2 v = __ldg(reinterpret_cast < const uint2 *> ( src )); 1817kx [ 0 ] = v . x ; kx [ 1 ] = v . y ; 1818#endif 1819} 1820const wh8 b = i8_to_h( kx ); 1821s = wmma_f16( qh [ kk ], b , s ); 1822if constexpr ( SPLIT ) s = wmma_f16( ql [ kk ], b , s ); 1823} 1824#pragma unroll 1825for ( int i = 0 ; i < 8 ; ++ i ) S . part [ warp ][PA_ROW( i , half )][ nt * 16 + col ] = s [ i ] * ksc ; 1826} 1827__syncthreads(); 1828// online softmax over the four groups' sum (fixed order): row t/8, 4 cells per thread 1829{ 1830const int r = t >> 3 , sub = t & 7 ; 1831float x [ 4 ], mx = - INFINITY ; 1832#pragma unroll 1833for ( int j = 0 ; j < 4 ; ++ j ) { 1834const int c = sub * 4 + j ; 1835// past the selection, or a masked cell (non-resident page, as in the decode kernel): no weight 1836x [ j ] = S . valid [ c ] ? ((( S . part [ 0 ][ r ][ c ] + S . part [ 1 ][ r ][ c ]) + S . part [ 2 ][ r ][ c ]) + S . part [ 3 ][ r ][ c ]) * qdown 1837: - INFINITY ; 1838mx = fmaxf( mx , x [ j ]); 1839} 1840#pragma unroll 1841for ( int o = 1 ; o < 8 ; o <<= 1 ) mx = fmaxf( mx , __shfl_xor_sync( 0xffffffffu , mx , o )); 1842const float m_old = S . mrow [ r ]; 1843const float m_new = fmaxf( m_old , mx ); 1844float sum = 0.0f ; 1845#pragma unroll 1846for ( int j = 0 ; j < 4 ; ++ j ) { 1847const float e = x [ j ] == - INFINITY ? 0.0f : exp2f( x [ j ] - m_new ); 1848S . p [ r ][ sub * 4 + j ] = e ; 1849sum += e ; 1850} 1851#pragma unroll 1852for ( int o = 1 ; o < 8 ; o <<= 1 ) sum += __shfl_xor_sync( 0xffffffffu , sum , o ); 1853if ( sub == 0 ) { 1854const float a = m_old == - INFINITY ? 0.0f : exp2f( m_old - m_new ); 1855S . alpha [ r ] = a ; 1856S . lsum [ r ] = fmaf( S . lsum [ r ], a , sum ); 1857S . mrow [ r ] = m_new ; 1858} 1859} 1860__syncthreads(); 1861// p.v over this wave's 64 dims: 4 tiles of 16 dims, 2 k-steps of 16 cells 1862{ 1863float vmax = S . vs [ warp ][ lane ]; 1864#pragma unroll 1865for ( int o = 16 ; o > 0 ; o >>= 1 ) vmax = fmaxf( vmax , __shfl_xor_sync( 0xffffffffu , vmax , o )); 1866const float vup = vmax > 0.0f ? 16384.0f / vmax : 0.0f , vdown = vmax * ( 1.0f / 16384.0f ); 1867wf8 tmp [ 4 ]; 1868#pragma unroll 1869for ( int j = 0 ; j < 4 ; ++ j ) tmp [ j ] = wf8 { 0.f , 0.f , 0.f , 0.f , 0.f , 0.f , 0.f , 0.f }; 1870#pragma unroll 1871for ( int ks = 0 ; ks < 2 ; ++ ks ) { 1872const int cb = ks * 16 + PA_KOFF( half ); // this lane's PA_KL cells 1873wh8 ah , al ; 1874#pragma unroll 1875for ( int i = 0 ; i < PA_KL ; ++ i ) { 1876const float pv = S . p [ col ][ cb + i ] * ( S . vs [ warp ][ cb + i ] * vup ); 1877const _Float16 hi = ( _Float16 ) pv ; 1878ah [ i ] = hi ; 1879al [ i ] = ( _Float16 ) ( pv - ( float ) hi ); 1880} 1881#pragma unroll 1882for ( int j = 0 ; j < 4 ; ++ j ) { 1883const int d = j * 16 + col ; 1884wh8 b ; 1885#pragma unroll 1886for ( int i = 0 ; i < PA_KL ; ++ i ) b [ i ] = ( _Float16 ) ( int ) ( int8_t ) S . v [ warp ][ cb + i ][ d ]; 1887tmp [ j ] = wmma_f16( ah , b , tmp [ j ]); 1888if constexpr ( SPLIT ) tmp [ j ] = wmma_f16( al , b , tmp [ j ]); 1889} 1890} 1891float a [ 8 ]; 1892#pragma unroll 1893for ( int i = 0 ; i < 8 ; ++ i ) a [ i ] = S . alpha [PA_ROW( i , half )]; 1894#pragma unroll 1895for ( int j = 0 ; j < 4 ; ++ j ) 1896#pragma unroll 1897for ( int i = 0 ; i < 8 ; ++ i ) acc [ j ][ i ] = fmaf( acc [ j ][ i ], a [ i ], tmp [ j ][ i ] * vdown ); 1898} 1899// no barrier here: `v`/`vs` are this wave's own, and `p`/`alpha`/`valid` are rewritten only after the next 1900// chunk's first barrier (which every wave reaches after its p.v) 1901} 1902float inv [ 8 ]; 1903#pragma unroll 1904for ( int i = 0 ; i < 8 ; ++ i ) { 1905const float l = S . lsum [PA_ROW( i , half )]; 1906inv [ i ] = l > 0.0f ? 1.0f / l : 0.0f ; 1907} 1908#pragma unroll 1909for ( int j = 0 ; j < 4 ; ++ j ) 1910#pragma unroll 1911for ( int i = 0 ; i < 8 ; ++ i ) { 1912const int row = PA_ROW( i , half ); 1913if ( row < G ) attn [( size_t ) row * HD + dim0 + j * 16 + col ] = acc [ j ][ i ] * inv [ i ]; 1914} 1915#else 1916__builtin_trap(); 1917#endif 1918} 1919 1920// gfx12 (RDNA4) and gfx11 (RDNA3 / RDNA3.5), only on request: the output differs from the default kernel's in its 1921// last bits 1922bool hip_wmma_usable() { 1923static const bool want = [] { 1924const char * e = std::getenv( "STRATA_HIP_WMMA" ); 1925return e != nullptr && e [ 0 ] == '1' ; 1926}(); 1927if (! want ) return false; 1928static int arch [ 64 ] = {}; // 0 unknown, 1 gfx11 / gfx12, 2 other 1929int dev = 0 ; 1930if (hipGetDevice( & dev ) != hipSuccess || dev < 0 || dev >= 64 ) { ( void ) hipGetLastError(); return false; } 1931if ( arch [ dev ] == 0 ) { 1932hipDeviceProp_t prop {}; 1933if (hipGetDeviceProperties( & prop , dev ) != hipSuccess ) { ( void ) hipGetLastError(); return false; } 1934arch [ dev ] = std::strncmp( prop . gcnArchName , "gfx12" , 5 ) == 0 || strata::kernels:: gfx_arch_is_gfx11_wmma ( prop . gcnArchName ) 1935? 1 : 2 ; 1936static bool told = false; 1937if (! told ) { 1938told = true; 1939std::fprintf( stderr , "strata: STRATA_HIP_WMMA: the prompt attention on matrix cores %s (%s)\n" , 1940arch [ dev ] == 1 ? "on" : "unavailable" , prop . gcnArchName ); 1941} 1942} 1943return arch [ dev ] == 1 ; 1944} 1945 1946bool launch_wmma( const float * q , const QsaAttnPools & pools , const int32_t * ids , const int32_t * steps , int64_t cap , 1947const QsaShapes & s , float * attn , int64_t n_q , cudaStream_t st ) { 1948const float scale_log2 = 1.4426950408889634f / sqrtf(( float ) HD ); 1949for ( int64_t q0 = 0 ; q0 < n_q ; q0 += 65535 ) { 1950const int64_t nb = n_q - q0 < 65535 ? n_q - q0 : 65535 ; 1951static const bool fast = [] { const char * e = std::getenv( "STRATA_PA_FAST" ); return e != nullptr && e [ 0 ] == '1' ; }(); 1952static const int64_t min_t = [] { const char * e = std::getenv( "STRATA_PF_SWITCH_MIN_T" ); return e ? ( int64_t ) std::atoll( e ) : ( int64_t ) 0 ; }(); 1953if ( fast && n_q >= min_t ) 1954prompt_attn_wmma_kernel < false > <<<dim3(( unsigned ) nb , ( unsigned ) s . n_head_kv ), THREADS , 0 , st > >>( 1955q + q0 * s . n_head * HD , pools , ids + q0 * cap , steps + q0 * kStepCount , ( int ) s . n_head_kv , 1956( int ) s . page_size , scale_log2 , attn + q0 * s . n_head * HD , ( int ) cap ); 1957else 1958prompt_attn_wmma_kernel < true > <<<dim3(( unsigned ) nb , ( unsigned ) s . n_head_kv ), THREADS , 0 , st > >>( 1959q + q0 * s . n_head * HD , pools , ids + q0 * cap , steps + q0 * kStepCount , ( int ) s . n_head_kv , 1960( int ) s . page_size , scale_log2 , attn + q0 * s . n_head * HD , ( int ) cap ); 1961} 1962const cudaError_t e = cudaGetLastError(); 1963if ( e != cudaSuccess ) { 1964std::fprintf( stderr , "qsa_prompt_attn_batch (wmma): %s\n" , cudaGetErrorString( e )); 1965std::exit( 1 ); 1966} 1967return true; 1968} 1969#endif 1970 1971} // namespace 1972 1973bool qsa_prompt_attn_batch( const float * q , const QsaAttnPools & pools , const int32_t * ids , const int32_t * steps , 1974int64_t cap , const QsaShapes & s , float * attn , int64_t n_q , void * stream ) { 1975if ( n_q <= 0 ) return true; 1976bool volta = false, turing = false; // per call, from the CURRENT device (a layer split can mix Turing with newer cards) 1977{ // sm_75 or newer: the MMA above compiles for both. sm_80+ runs the cp.async kernel (launch_i8); Turing has 1978// no cp.async, so it runs the v1 kernel (launch<1>, same accuracy, another summation order). An older card 1979// keeps the old kernel. 1980// #371: the compute capability with its minor - sm_70 (V100) has no m16n8k8 (the kernels trap below sm_75) 1981#if defined( STRATA_HIP_GFX906 ) 1982return false; // gfx906: the tensor-core and WMMA kernels are not for it; the FP32 kernel runs 1983#endif 1984static int cc [ 64 ] = {}; 1985int dev = 0 ; 1986/* 1987DPCT1026: The call to cudaGetLastError was removed because this 1988functionality is redundant in SYCL. 1989*/ 1990if (DPCT_CHECK_ERROR( dev = dpct::get_current_device_id()) != 0 || 1991dev < 0 || dev >= 64 ) { 1992; return false; 1993} 1994if ( cc [ dev ] == 0 ) { 1995int major = 0 , minor = 0 ; 1996if (DPCT_CHECK_ERROR( 1997major = dpct::get_device( dev ).get_major_version()) != 0 || 1998DPCT_CHECK_ERROR( 1999minor = dpct::get_device( dev ).get_minor_version()) != 0 ) { 2000/* 2001DPCT1026: The call to cudaGetLastError was removed because 2002this functionality is redundant in SYCL. 2003*/ 2004return false; 2005} 2006// STRATA_QSA_WARP=1|attn (an A/B arm): the pre-sm_80 kernels on any card, as RTX 20 runs them 2007const char * w = std::getenv( "STRATA_QSA_WARP" ); 2008cc [ dev ] = w && (!std::strcmp( w , "1" ) || !std::strcmp( w , "attn" )) ? 75 2009: 10 * strata::cc_major_of( major ) + strata::cc_minor_of( minor ); 2010} 2011( void ) cc [ dev ]; 2012// SYCL: the mma.sync kernel below is not ported (upstream's Turing/sm_80 split - `turing` - does not 2013// apply); its XMX port takes the same arguments 2014if (qsa_prompt_attn_esimd( q , pools , ids , steps , cap , s , attn , n_q , stream )) return true; 2015if (qsa_prompt_attn_xmx( q , pools , ids , steps , cap , s , attn , n_q , stream )) return true; 2016return false; // the caller takes the older kernel 2017} 2018#if defined( __HIPCC__ ) 2019// the tensor-core kernels are compiled out on AMD (its major version is not a CUDA sm); RDNA4 has its own int8-KV 2020// matrix-core kernel, opt-in (STRATA_HIP_WMMA=1); everything else keeps the old kernel 2021( void ) turing ; ( void ) volta ; 2022if ( pools . k_q != nullptr && pools . v_q != nullptr && pools . k_scale != nullptr && pools . v_scale != nullptr && 2023pools . k_q4 == nullptr && pools . v_q4 == nullptr && s . head_dim == HD && s . n_head == ( int64_t ) G * s . n_head_kv && 2024cap > 0 && ids && steps && pools . page_table && hip_wmma_usable()) 2025return launch_wmma( q , pools , ids , steps , cap , s , attn , n_q , ( cudaStream_t ) stream ); 2026return false; 2027#endif 2028if ( s . head_dim != HD || s . n_head != ( int64_t ) G * s . n_head_kv || cap <= 0 || ! ids || ! steps || ! pools . page_table ) 2029return false; 2030dpct:: queue_ptr st = strata::q_of( stream ); 2031if ( pools . k_q4 != nullptr ) { // Q4_0 K and V (--kv q4_0): mode 4. STRATA_PROMPT_ATTN_Q4=0: the old kernel (A/B) 2032static const bool q4_off = [] { 2033const char * v = std::getenv( "STRATA_PROMPT_ATTN_Q4" ); 2034return v != nullptr && v [ 0 ] == '0' ; 2035}(); 2036// sm_80+ only: on Turing mode 4 would run as pairs of m16n8k8 MMAs, which no parity run has checked yet 2037if ( q4_off || turing || pools . v_q4 == nullptr ) return false; 2038return launch < 4 > ( q , pools , ids , steps , cap , s , attn , n_q , st ); 2039} 2040if ( pools . k_q != nullptr && pools . v_q4 != nullptr ) { // hybrid K8V4: int8 K + dequantized-q4 V 2041if (! pools . k_scale ) return false; 2042if ( volta ) return launch70 < 3 > ( q , pools , ids , steps , cap , s , attn , n_q , st ); 2043return launch < 3 > ( q , pools , ids , steps , cap , s , attn , n_q , st ); 2044} 2045if ( pools . k_q != nullptr ) { 2046if (! pools . v_q || ! pools . k_scale || ! pools . v_scale ) return false; 2047// STRATA_PROMPT_ATTN_V1=1 (debug): the first version, same accuracy, another summation order - the control 2048// for how far the model amplifies an FP32-level change. Turing always takes it: v2's cp.async does not 2049// exist before sm_80. 2050static const bool v1 = std::getenv( "STRATA_PROMPT_ATTN_V1" ) != nullptr ; 2051if ( volta ) return launch70 < 1 > ( q , pools , ids , steps , cap , s , attn , n_q , st ); 2052if ( v1 || turing ) return launch < 1 > ( q , pools , ids , steps , cap , s , attn , n_q , st ); 2053return launch_i8( q , pools , ids , steps , cap , s , attn , n_q , st ); 2054} 2055if (! pools . k_pool || ! pools . v_pool ) return false; 2056if ( volta ) return launch70 < 0 > ( q , pools , ids , steps , cap , s , attn , n_q , st ); 2057return launch < 0 > ( q , pools , ids , steps , cap , s , attn , n_q , st ); 2058} 2059 2060} // namespace strata::kernels