okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
86bed1c92
main
1// src/kernels/cuda/kv_q4.cu - see include/strata/kernels/kv_q4.hpp. Q4_0 KV with Walsh-Hadamard rotation 2// (from PR #21 by code-martin; KV-streaming integration and the deterministic group maximum added on merge). 3#define DPCT_PROFILING_ENABLED 4#include <sycl/sycl.hpp> 5#include "strata/kprof.hpp" 6#include <dpct/dpct.hpp> 7#include "strata/sycl_queue.hpp" 8#include "strata/kernels/kv_q4.hpp" 9#include "strata/kernels/f16_bits.hpp" 10#include "strata/kernels/kv_stream.hpp" 11 12#include <cstdio> 13#include <cstdlib> 14 15namespace strata::kernels { 16namespace { 17 18void check (const char * what ) { 19/* 20DPCT1010: SYCL uses exceptions to report errors and does not use the 21error codes. The cudaGetLastError function call was replaced with 0. You 22need to rewrite this code. 23*/ 24const dpct::err0 e = 0 ; 25} 26 27// Fast Walsh-Hadamard Transform for N = 256: one warp per row, 8 values per lane in registers. 28// Orthonormal (scale 1/sqrt(256) = 1/16), so it is its own inverse. 29__dpct_inline__ void fwht256_kernel (const float * __restrict__src , 30float * __restrict__dst ,int64_t n_rows , 31float scale ) { 32auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item < 3 > (); 33constexpr int warp_size = 32 ; 34constexpr int N = 256 ; 35constexpr int el_w = N /warp_size ;// 8 36 37const int64_t r = 38 (int64_t )item_ct1 .get_group (2 )* item_ct1 .get_local_range (1 )+ 39item_ct1 .get_local_id (1 ); 40if (r >=n_rows )return ; 41 42const float * row_src = src + r * N ; 43float * row_dst = dst + r * N ; 44 45float reg [el_w ]; 46const int lane = item_ct1 .get_local_id (2 ); 47 48#pragma unroll 49for (int i = 0 ;i < el_w ;++ i )reg [i ]= row_src [i * warp_size + lane ]* scale ; 50 51// the low 5 index bits live across lanes 52#pragma unroll 53for (int h = 1 ;h < warp_size ;h *=2 ) { 54#pragma unroll 55for (int j = 0 ;j < el_w ;++ j ) { 56const float val = reg [j ]; 57/* 58DPCT1108: '__shfl_xor_sync' was migrated with the experimental 59feature masked sub_group function which may not be supported by all 60compilers or runtimes. You may need to adjust the code. 61*/ 62const float val2 = dpct::experimental::permute_sub_group_by_xor ( 630xffffffffu , sycl::ext::oneapi::this_work_item::get_sub_group (), 64val ,h ); 65reg [j ]= (lane & h )== 0 ?val + val2 :val2 - val ; 66 } 67 } 68// the high 3 bits across each lane's registers 69#pragma unroll 70for (int h = warp_size ;h < N ;h *=2 ) { 71const int step = h /warp_size ; 72#pragma unroll 73for (int j = 0 ;j < el_w ;j += 2 * step ) { 74#pragma unroll 75for (int k = 0 ;k < step ;++ k ) { 76const float x = reg [j + k ]; 77const float y = reg [j + k + step ]; 78reg [j + k ]= x + y ; 79reg [j + k + step ]= x - y ; 80 } 81 } 82 } 83#pragma unroll 84for (int i = 0 ;i < el_w ;++ i )row_dst [i * warp_size + lane ]= reg [i ]; 85} 86 87// One 32-value group in one warp (lane = element), ggml's q4_0: d = (the value of largest |x|) / -8, 88// q = clamp(trunc(x / d + 8.5), 0, 15). Returns the scale bits; `byte` is lane t's packed byte for t < 16 89// (element t in the low nibble, t + 16 in the high one). Ties in |x| resolve to the larger value in EVERY lane, 90// so all lanes agree on d (a plain `a > amax` could leave lanes with opposite signs and one block two scales). 91__dpct_inline__ uint16_t q4_group (float x ,int lane ,uint8_t & byte ) { 92float amax = sycl::fabs (x ),mval = x ; 93#pragma unroll 94for (int o = 16 ;o > 0 ;o >>=1 ) { 95/* 96DPCT1108: '__shfl_xor_sync' was migrated with the experimental 97feature masked sub_group function which may not be supported by all 98compilers or runtimes. You may need to adjust the code. 99*/ 100const float a = dpct::experimental::permute_sub_group_by_xor ( 1010xffffffffu , sycl::ext::oneapi::this_work_item::get_sub_group (), 102amax ,o ); 103/* 104DPCT1108: '__shfl_xor_sync' was migrated with the experimental 105feature masked sub_group function which may not be supported by all 106compilers or runtimes. You may need to adjust the code. 107*/ 108const float v = dpct::experimental::permute_sub_group_by_xor ( 1090xffffffffu , sycl::ext::oneapi::this_work_item::get_sub_group (), 110mval ,o ); 111if (a > amax || (a == amax && v > mval )) {amax = a ;mval = v ; } 112 } 113const float d = mval /-8.0f ; 114const float id = d != 0.0f ?1.0f /d :0.0f ; 115int q = sycl::vec < float ,1 > {(x * id + 8.5f )} 116 .convert < int , sycl::rounding_mode::rtz > ()[0 ]; 117const uint8_t qc = (uint8_t ) (q < 0 ?0 : (q > 15 ?15 :q )); 118/* 119DPCT1108: '__shfl_down_sync' was migrated with the experimental feature 120masked sub_group function which may not be supported by all compilers or 121runtimes. You may need to adjust the code. 122*/ 123const uint8_t qhi = dpct::experimental::shift_sub_group_left ( 1240xffffffffu , sycl::ext::oneapi::this_work_item::get_sub_group (),qc , 12516 ); 126byte = (uint8_t ) (qc | (qhi <<4 )); 127 (void )lane ; 128return f16_from_f32 (d ); 129} 130 131__dpct_inline__ void q4_store (uint8_t * pool ,long long row ,int b ,int lane , 132uint16_t d ,uint8_t byte ) { 133block_q4_0 * blk = reinterpret_cast < block_q4_0 *> (pool + row * (long long )sizeof (block_q4_0 )* 8 )+ b ; 134if (lane == 0 )blk -> d = d ; 135if (lane < 16 )blk -> qs [lane ]= byte ; 136} 137 138// One block = one 32-value group of one KV head of K (plane 0) or V (plane 1) for token step_idx; 32 threads. 139__dpct_inline__ void 140kv_append_q4_kernel (uint8_t * __restrict__k_q4 ,uint8_t * __restrict__v_q4 , 141const int32_t * __restrict__table , 142const int32_t * __restrict__step ,int step_stride , 143int planes ,const float * __restrict__kcur , 144const float * __restrict__vcur ,int kv_heads ,int head_dim , 145int page_size ,KvHostPools host ) { 146auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item < 3 > (); 147const int step_idx = (int )(item_ct1 .get_group (0 ) / (unsigned )planes ); 148const bool is_v = (item_ct1 .get_group (0 ) % (unsigned )planes )== 1u ; 149/* 150DPCT1098: The '*' expression is used instead of the __ldg call. These 151two expressions do not provide the exact same functionality. Check the 152generated code for potential precision and/or performance issues. 153*/ 154const long long pos = 155 (long long )* (step + (long long )step_idx * step_stride + kStepPos ); 156const int h = item_ct1 .get_group (2 ),b = item_ct1 .get_group (1 ), 157t = item_ct1 .get_local_id (2 ); 158const long long step_off = (long long )step_idx * kv_heads * head_dim ; 159const float x = (is_v ?vcur :kcur )[step_off + h * head_dim + b * QK4_0 + t ]; 160uint8_t byte ; 161const uint16_t d = q4_group (x ,t ,byte ); 162const long long page = (long long )table [pos /page_size ]; 163if (page >=0 )q4_store (is_v ?v_q4 :k_q4 , (page * kv_heads + h )* page_size + (pos %page_size ),b ,t ,d ,byte ); 164if (host .k_q4 != nullptr ) 165q4_store (is_v ?host .v_q4 :host .k_q4 , ((pos /page_size )* kv_heads + h )* page_size + (pos %page_size ),b ,t , 166d ,byte ); 167} 168 169// The prompt path: grid (T, kv_heads, groups), K then V; also into the staging pool (identity layout) when given. 170__dpct_inline__ void kv_append_q4_batch_kernel ( 171uint8_t * __restrict__k_q4 ,uint8_t * __restrict__v_q4 , 172const int32_t * __restrict__table ,int64_t pos0 , 173const float * __restrict__K ,const float * __restrict__V ,int kv_heads , 174int head_dim ,int page_size ,int is_v_grid ,KvHostPools host , 175KvHostPools stage ) { 176auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item < 3 > (); 177const long long t = item_ct1 .get_group (2 ); 178const long long pos = pos0 + t ; 179const int h = item_ct1 .get_group (1 ),b = item_ct1 .get_group (0 ), 180th = item_ct1 .get_local_id (2 ); 181const bool is_v = is_v_grid != 0 ; 182const float x = (is_v ?V :K )[t * (kv_heads * head_dim )+ h * head_dim + b * QK4_0 + th ]; 183uint8_t byte ; 184const uint16_t d = q4_group (x ,th ,byte ); 185const long long page = (long long )table [pos /page_size ]; 186const long long row_id = ((pos /page_size )* kv_heads + h )* page_size + (pos %page_size ); 187if (page >=0 )q4_store (is_v ?v_q4 :k_q4 , (page * kv_heads + h )* page_size + (pos %page_size ),b ,th ,d ,byte ); 188if (host .k_q4 != nullptr )q4_store (is_v ?host .v_q4 :host .k_q4 ,row_id ,b ,th ,d ,byte ); 189if (stage .k_q4 != nullptr )q4_store (is_v ?stage .v_q4 :stage .k_q4 ,row_id ,b ,th ,d ,byte ); 190} 191 192// Gather step[kStepWidth] cells into FP16 scratch (the non-fused attention paths) 193__dpct_inline__ void kv_gather_q4_kernel ( 194const uint8_t * __restrict__k_q4 ,const uint8_t * __restrict__v_q4 , 195const int32_t * __restrict__table ,const int32_t * __restrict__ids , 196const int32_t * __restrict__step ,int kv_heads ,int head_dim ,int page_size , 197uint16_t * __restrict__k_scratch ,uint16_t * __restrict__v_scratch ) { 198/* 199DPCT1098: The '*' expression is used instead of the __ldg call. These 200two expressions do not provide the exact same functionality. Check the 201generated code for potential precision and/or performance issues. 202*/ 203auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item < 3 > (); 204const long long n_ids = (long long )* (step + kStepWidth ); 205const int blocks_per_head = head_dim /QK4_0 ;// 8 206const int bytes_per_head = blocks_per_head * sizeof (block_q4_0 );// 144 207const long long total_blocks = n_ids * kv_heads * blocks_per_head ; 208 209const long long blk_idx = 210 (long long )item_ct1 .get_group (2 )* item_ct1 .get_local_range (1 )+ 211item_ct1 .get_local_id (1 ); 212if (blk_idx >=total_blocks )return ; 213 214const int t = item_ct1 .get_local_id (2 ); 215const long long id = blk_idx / (kv_heads * blocks_per_head ); 216const int rem = (int ) (blk_idx % (kv_heads * blocks_per_head )); 217const int h = rem /blocks_per_head ; 218const int b = rem %blocks_per_head ; 219 220const int cell = ids [id ]; 221const long long page = (long long )table [cell /page_size ]; 222const long long row = (page * kv_heads + h )* page_size + (cell %page_size ); 223 224const block_q4_0 * k_blk = reinterpret_cast < const block_q4_0 *> (k_q4 + row * bytes_per_head )+ b ; 225const block_q4_0 * v_blk = reinterpret_cast < const block_q4_0 *> (v_q4 + row * bytes_per_head )+ b ; 226const float kd = f32_from_f16 (k_blk -> d ); 227const float vd = f32_from_f16 (v_blk -> d ); 228const int j = t < 16 ?t : (t - 16 ); 229const uint8_t k_byte = k_blk -> qs [j ]; 230const uint8_t v_byte = v_blk -> qs [j ]; 231const int kq = (t < 16 ) ? ((k_byte & 0x0F )- 8 ) : ((k_byte >>4 )- 8 ); 232const int vq = (t < 16 ) ? ((v_byte & 0x0F )- 8 ) : ((v_byte >>4 )- 8 ); 233const long long dst_offset = ((id * kv_heads + h )* head_dim )+ (b * QK4_0 + t ); 234k_scratch [dst_offset ]= f16_from_f32 ((float )kq * kd ); 235v_scratch [dst_offset ]= f16_from_f32 ((float )vq * vd ); 236} 237 238void need_256 (const QsaShapes & s ,const char * what ) { 239if (s .head_dim != 256 ) { 240 std::fprintf (stderr ,"%s: head_dim must be 256 (the Hadamard transform's size)\n" ,what ); 241 std::exit (1 ); 242 } 243} 244 245}// namespace 246 247void fwht256_cuda (const float * src ,float * dst ,int64_t n_rows ,void * stream ) { 248if (n_rows <=0 )return ; 249const int rows_per_block = 4 ; 250const int64_t num_blocks = (n_rows + rows_per_block - 1 ) /rows_per_block ; 251 { 252auto exp_props = sycl::ext::oneapi::experimental::properties { 253 sycl::ext::oneapi::experimental::use_root_sync }; 254 255 strata::kprof::kp (strata::q_of (stream ),__FILE__ ,__func__ ,__LINE__ ) 256-> submit ([& ](sycl::handler & cgh ) { 257auto ct3 = 1.0f /16.0f ; 258 259cgh .parallel_for < dpct_kernel_name < class fwht256_kernel_d551a1 >> ( 260 sycl::nd_range < 3 > (sycl::range (1 ,1 , (unsigned )num_blocks )* 261 sycl::range (1 ,rows_per_block ,32 ), 262 sycl::range (1 ,rows_per_block ,32 )), 263exp_props , 264 [= ](sycl::nd_item < 3 > item_ct1 ) 265 [[sycl ::reqd_sub_group_size (32 )]] { 266fwht256_kernel (src ,dst ,n_rows ,ct3 ); 267 }); 268 }); 269 } 270check ("fwht256 launch" ); 271} 272 273void kv_append_q4_steps (uint8_t * k_q4 ,uint8_t * v_q4 ,const int32_t * page_table ,const int32_t * step , 274int step_stride ,int n_steps ,const float * kcur ,const float * vcur ,const QsaShapes & s , 275void * stream ,const KvHostPools * host ) { 276if (n_steps <=0 )return ; 277need_256 (s ,"kv_append_q4" ); 278const int planes = (v_q4 == nullptr || (v_q4 == k_q4 && vcur == kcur )) ?1 :2 ; 279const dpct::dim3 grid ((unsigned )s .n_head_kv , (unsigned )(s .head_dim /QK4_0 ), 280 (unsigned )(n_steps * planes )); 281 { 282auto exp_props = sycl::ext::oneapi::experimental::properties { 283 sycl::ext::oneapi::experimental::use_root_sync }; 284 285 strata::kprof::kp (strata::q_of (stream ),__FILE__ ,__func__ ,__LINE__ ) 286-> submit ([& ](sycl::handler & cgh ) { 287KvHostPools host_host_KvHostPools_ct11 = 288host ?* host :KvHostPools {}; 289 290cgh .parallel_for < 291dpct_kernel_name < class kv_append_q4_kernel_f256b8 >> ( 292 sycl::nd_range < 3 > (grid * sycl::range (1 ,1 ,32 ), 293 sycl::range (1 ,1 ,32 )), 294exp_props , 295 [= ](sycl::nd_item < 3 > item_ct1 ) 296 [[sycl ::reqd_sub_group_size (32 )]] { 297kv_append_q4_kernel ( 298k_q4 ,v_q4 ,page_table ,step ,step_stride , 299planes ,kcur ,vcur , (int )s .n_head_kv , 300 (int )s .head_dim , (int )s .page_size , 301host_host_KvHostPools_ct11 ); 302 }); 303 }); 304 } 305check ("kv_append_q4 launch" ); 306} 307 308void kv_append_q4_step (uint8_t * k_q4 ,uint8_t * v_q4 ,const int32_t * page_table ,const int32_t * step , 309const float * kcur ,const float * vcur ,const QsaShapes & s ,void * stream , 310const KvHostPools * host ) { 311kv_append_q4_steps (k_q4 ,v_q4 ,page_table ,step ,0 ,1 ,kcur ,vcur ,s ,stream ,host ); 312} 313 314void kv_append_q4 (uint8_t * k_q4 ,uint8_t * v_q4 ,const int32_t * page_table ,int64_t pos0 ,int64_t T ,const float * K , 315const float * V ,const QsaShapes & s ,void * stream ,const KvHostPools * host ,const KvHostPools * stage ) { 316if (T <=0 )return ; 317need_256 (s ,"kv_append_q4" ); 318const dpct::dim3 grid ((unsigned )T , (unsigned )s .n_head_kv , 319 (unsigned )(s .head_dim /QK4_0 )); 320 dpct::queue_ptr cs = strata::q_of (stream ); 321const KvHostPools h = host ?* host :KvHostPools {},st = stage ?* stage :KvHostPools {}; 322for (int is_v = 0 ;is_v < 2 ;++ is_v ) 323 { 324auto exp_props = sycl::ext::oneapi::experimental::properties { 325 sycl::ext::oneapi::experimental::use_root_sync }; 326 327 strata::kprof::kp (cs ,__FILE__ ,__func__ ,__LINE__ )-> template parallel_for < 328dpct_kernel_name < class kv_append_q4_batch_kernel_11c37a >> ( 329 sycl::nd_range < 3 > (grid * sycl::range (1 ,1 ,32 ), 330 sycl::range (1 ,1 ,32 )), 331exp_props , 332 [= ](sycl::nd_item < 3 > item_ct1 ) [[sycl ::reqd_sub_group_size (32 )]] { 333kv_append_q4_batch_kernel (k_q4 ,v_q4 ,page_table ,pos0 ,K ,V , 334 (int )s .n_head_kv , (int )s .head_dim , 335 (int )s .page_size ,is_v ,h ,st ); 336 }); 337 } 338check ("kv_append_q4 batch launch" ); 339} 340 341void kv_gather_q4_step (const uint8_t * k_q4 ,const uint8_t * v_q4 ,const int32_t * page_table ,const int32_t * ids , 342const int32_t * step ,int64_t max_ids ,const QsaShapes & s ,uint16_t * k_scratch , 343uint16_t * v_scratch ,void * stream ) { 344if (max_ids <=0 )return ; 345const int blocks_per_head = (int ) (s .head_dim /QK4_0 ); 346const int64_t total_blocks = max_ids * s .n_head_kv * blocks_per_head ; 347const int rows_per_block = 4 ; 348const unsigned num_blocks = (unsigned ) ((total_blocks + rows_per_block - 1 ) /rows_per_block ); 349 { 350auto exp_props = sycl::ext::oneapi::experimental::properties { 351 sycl::ext::oneapi::experimental::use_root_sync }; 352 353 strata::kprof::kp (strata::q_of (stream ),__FILE__ ,__func__ ,__LINE__ ) 354-> template parallel_for < dpct_kernel_name < class kv_gather_q4_kernel_300c16 >> ( 355 sycl::nd_range < 3 > (sycl::range (1 ,1 ,num_blocks )* 356 sycl::range (1 ,rows_per_block ,32 ), 357 sycl::range (1 ,rows_per_block ,32 )), 358exp_props , [= ](sycl::nd_item < 3 > item_ct1 ) { 359kv_gather_q4_kernel (k_q4 ,v_q4 ,page_table ,ids ,step , 360 (int )s .n_head_kv , (int )s .head_dim , 361 (int )s .page_size ,k_scratch ,v_scratch ); 362 }); 363 } 364check ("kv_gather_q4 launch" ); 365} 366 367}// namespace strata::kernels