okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
86bed1c92
main
1// Numerical contract: pinned ggml/src/ggml-cuda/rope.cu, rope_multi/rope_yarn. 2// Text positions are equal across the four IMRoPE sections, so section routing 3// reduces to the one position associated with each contiguous row. 4// MIT License 5// 6// Copyright (c) 2023-2026 The ggml authors 7// 8// Permission is hereby granted, free of charge, to any person obtaining a copy 9// of this software and associated documentation files (the "Software"), to deal 10// in the Software without restriction, including without limitation the rights 11// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12// copies of the Software, and to permit persons to whom the Software is 13// furnished to do so, subject to the following conditions: 14// 15// The above copyright notice and this permission notice shall be included in all 16// copies or substantial portions of the Software. 17// 18// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 24// SOFTWARE. 25#define DPCT_PROFILING_ENABLED 26#include <sycl/sycl.hpp> 27#include "strata/kprof.hpp" 28#include <dpct/dpct.hpp> 29#include "strata/sycl_queue.hpp" 30#include "strata/kernels/native_rope.hpp" 31#include "strata/kernels/mrope.hpp" 32#include <atomic> 33#include <cmath> 34#include <cstdint> 35#include <cstdlib> 36#include <limits> 37#include <stdexcept> 38 39namespace strata::kernels { 40namespace { 41std::atomic < bool > enabled {false}; 42bool overlaps (const void * a ,size_t an ,const void * b ,size_t bn ) { 43auto x = reinterpret_cast < uintptr_t > (a ),y = reinterpret_cast < uintptr_t > (b ); 44return x <=y ?y - x < an :x - y < bn ; 45} 46// TAB (#280, STRATA_ROPE_TABLE=1): the angles from the session's float64 table. The host launches <false> whenever 47// no table applies - the default - so the default kernel is 0.1.31's code exactly (the table read is not in it; 48// with it merely skipped at run time, the compiled default path changed its results). 49template < bool TAB > 50__dpct_inline__ void apply (const float * x ,float * out ,int rows ,int width , 51int n_rot ,float theta_scale ,float freq_scale , 52float corr_low ,float corr_high ,float ext_factor , 53float mscale ,const int * positions , 54const int32_t * mtab ,RopeTab rt ) { 55auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item < 3 > (); 56const int row = item_ct1 .get_group (1 ); 57const int pair = item_ct1 .get_group (2 )* item_ct1 .get_local_range (2 )+ 58item_ct1 .get_local_id (2 ); 59if (row >=rows || pair >=width /2 )return ; 60const size_t start = size_t (row )* width ; 61if (pair >=n_rot /2 ) { 62if (x != out ) { 63out [start + 2 * pair ]= x [start + 2 * pair ]; 64out [start + 2 * pair + 1 ]= x [start + 2 * pair + 1 ]; 65 } 66return ; 67 } 68float c ,s ; 69if (!(TAB && rope_tab_cs (rt ,mrope_pos (mtab ,positions [row ],pair ),pair ,c ,s ))) { 70const float theta_extrap = mrope_pos (mtab ,positions [row ],pair )* 71 dpct::pow (theta_scale ,float (pair )); 72rope_scaled_angle (theta_extrap ,freq_scale ,corr_low ,corr_high ,ext_factor ,mscale ,pair ,c ,s ); 73 } 74const float a = x [start + pair ],b = x [start + pair + n_rot /2 ]; 75out [start + pair ]= a * c - b * s ; 76out [start + pair + n_rot /2 ]= a * s + b * c ; 77} 78 79template < bool TAB > 80__dpct_inline__ void 81norm_rope_kernel (const float * x ,int in_stride ,const float * __restrict__gamma , 82float * out ,int n_cols ,int n_rot ,float epsilon , 83float theta_scale ,float freq_scale ,float corr_low , 84float corr_high ,float ext_factor ,float mscale , 85const int * positions ,const int32_t * mtab ,RopeTab rt ) { 86auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item < 3 > (); 87const int tid = item_ct1 .get_local_id (2 ); 88const int row = item_ct1 .get_group (2 ); 89const float * in_row = x + size_t (row )* in_stride ; 90float * out_row = out + size_t (row )* n_cols ; 91float partial = 0.0f ; 92for (size_t col = tid ;col < size_t (n_cols );col += 256 ) { 93const float xv = in_row [col ]; 94partial += xv * xv ; 95 } 96const int half_rot = n_rot /2 ; 97const float x_tid = tid < n_cols ?in_row [tid ] :0.0f ; 98const float x_hi = tid < half_rot ?in_row [tid + half_rot ] :0.0f ; 99auto & sums = 100* sycl::ext::oneapi::group_local_memory_for_overwrite < float [32 ]> ( 101 sycl::ext::oneapi::this_work_item::get_work_group < 3 > ()); 102#pragma unroll 103for (int offset = 16 ;offset ;offset >>=1 ) 104/* 105DPCT1108: '__shfl_xor_sync' was migrated with the experimental 106feature masked sub_group function which may not be supported by all 107compilers or runtimes. You may need to adjust the code. 108*/ 109partial += dpct::experimental::permute_sub_group_by_xor ( 1100xffffffffu , sycl::ext::oneapi::this_work_item::get_sub_group (), 111partial ,offset ); 112const int lane = tid %32 ; 113if (lane == 0 )sums [tid /32 ]= partial ; 114/* 115DPCT1065: Consider replacing sycl::nd_item::barrier() with 116sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better 117performance if there is no access to global memory. 118*/ 119item_ct1 .barrier (); 120partial = lane < 256 /32 ?sums [lane ] :0.0f ; 121#pragma unroll 122for (int offset = 16 ;offset ;offset >>=1 ) 123/* 124DPCT1108: '__shfl_xor_sync' was migrated with the experimental 125feature masked sub_group function which may not be supported by all 126compilers or runtimes. You may need to adjust the code. 127*/ 128partial += dpct::experimental::permute_sub_group_by_xor ( 1290xffffffffu , sycl::ext::oneapi::this_work_item::get_sub_group (), 130partial ,offset ); 131const float mean = partial /n_cols ; 132const float scale = sycl::rsqrt (mean + epsilon ); 133if (tid >=n_rot && tid < n_cols ) { 134out_row [tid ]= (scale * x_tid )* gamma [tid ]; 135 }else if (tid < half_rot ) { 136const int pair = tid ; 137float a = (scale * x_tid )* gamma [pair ]; 138float b = (scale * x_hi )* gamma [pair + half_rot ]; 139#if defined(DPCT_COMPATIBILITY_TEMP )&& !defined(__HIP_DEVICE_COMPILE__ ) 140#if defined(__SYCL_DEVICE_ONLY__ )&& defined(__NVPTX__ ) 141 asmvolatile ("mov.f32 %0, %1;" :"=f" (a ) :"f" (a )); 142#else 143a = a ; 144#endif 145#if defined(__SYCL_DEVICE_ONLY__ )&& defined(__NVPTX__ ) 146 asmvolatile ("mov.f32 %0, %1;" :"=f" (b ) :"f" (b )); 147#else 148b = b ; 149#endif 150#endif 151float c ,s ; 152if (!(TAB && rope_tab_cs (rt ,mrope_pos (mtab ,positions [row ],pair ),pair ,c ,s ))) { 153const float theta_extrap = mrope_pos (mtab ,positions [row ],pair )* 154 dpct::pow (theta_scale ,float (pair )); 155rope_scaled_angle (theta_extrap ,freq_scale ,corr_low ,corr_high ,ext_factor ,mscale ,pair ,c ,s ); 156 } 157float bs = b * s ; 158float bc = b * c ; 159#if defined(DPCT_COMPATIBILITY_TEMP )&& !defined(__HIP_DEVICE_COMPILE__ ) 160#if defined(__SYCL_DEVICE_ONLY__ )&& defined(__NVPTX__ ) 161 asmvolatile ("mov.f32 %0, %1;" :"=f" (bs ) :"f" (bs )); 162#else 163bs = bs ; 164#endif 165#if defined(__SYCL_DEVICE_ONLY__ )&& defined(__NVPTX__ ) 166 asmvolatile ("mov.f32 %0, %1;" :"=f" (bc ) :"f" (bc )); 167#else 168bc = bc ; 169#endif 170#endif 171out_row [pair ]= sycl::fma (a ,c ,- bs ); 172out_row [pair + half_rot ]= sycl::fma (a ,s ,bc ); 173 } 174} 175} 176// one table per device (a layer split runs the rope kernels on several): set and read for the current device 177namespace { 178constexpr int kMropeDevices = 64 ; 179std::atomic < const int32_t *> mrope_tab [kMropeDevices ]= {}; 180int mrope_dev ()try { 181int d = 0 ; 182if (DPCT_CHECK_ERROR (d = dpct::get_current_device_id ())!= 0 || d < 0 || 183d >=kMropeDevices )d = 0 ; 184return d ; 185} 186catch (sycl::exception const & exc ) { 187 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 188 <<", line:" <<__LINE__ << std::endl ; 189 std::exit (1 ); 190} 191}// namespace 192void mrope_table_set (const int32_t * device_table ) {mrope_tab [mrope_dev ()].store (device_table , std::memory_order_relaxed ); } 193const int32_t * mrope_table () {return mrope_tab [mrope_dev ()].load (std::memory_order_relaxed ); } 194namespace { 195// #280: the float64 angle table of each device, set at session init (before any graph is captured) 196struct RopeReg { 197RopeTab tab ; 198RopeScaling scaling ; 199}; 200RopeReg rope_tab [kMropeDevices ]= {}; 201bool same_scaling (const RopeScaling & a ,const RopeScaling & b ) { 202return a .type == b .type && a .freq_base == b .freq_base && a .factor == b .factor && a .freq_scale_in == b .freq_scale_in && 203a .orig_ctx == b .orig_ctx && a .ext_factor == b .ext_factor && a .attn_factor == b .attn_factor && 204a .beta_fast == b .beta_fast && a .beta_slow == b .beta_slow ; 205} 206// opt-in: STRATA_ROPE_TABLE=1 (the table's angles differ from the fast-math ones in the last bits, so outputs move) 207bool rope_table_enabled () { 208static const bool on = [] { 209const char * e = std::getenv ("STRATA_ROPE_TABLE" ); 210return e != nullptr && e [0 ]== '1' ; 211 }(); 212return on ; 213} 214}// namespace 215void rope_table_set (const float * cos_tab ,const float * sin_tab ,int max_pos ,const RopeScaling & scaling ) { 216rope_tab [mrope_dev ()]= RopeReg {RopeTab {cos_tab ,sin_tab ,max_pos },scaling }; 217} 218void rope_table_release (const float * cos_tab ) { 219// every device's entry that points at it (the caller may free it from another current device) 220for (RopeReg & r :rope_tab ) 221if (cos_tab != nullptr && r .tab .cos == cos_tab )r = RopeReg {}; 222} 223RopeTab rope_table_for (const RopeScaling & scaling ) { 224if (!rope_table_enabled ())return {}; 225const RopeReg & r = rope_tab [mrope_dev ()]; 226return r .tab .cos != nullptr && same_scaling (r .scaling ,scaling ) ?r .tab :RopeTab {}; 227} 228void native_rope_set_enabled (bool value ) {enabled .store (value , std::memory_order_relaxed ); } 229bool native_rope_enabled () {return enabled .load (std::memory_order_relaxed ); } 230bool native_norm_rope_usable (int head_dim ,int n_rot ) { 231static const bool on = [] { 232const char * off = std::getenv ("STRATA_NO_NORM_ROPE" ); 233if (off != nullptr && off [0 ]!= '\0' && off [0 ]!= '0' )return false; 234#if defined(__HIPCC__ ) 235const char * v = std::getenv ("STRATA_NORM_ROPE" );// AMD: opt in until rope_parity check 6 passes there 236return v != nullptr && v [0 ]!= '\0' && v [0 ]!= '0' ; 237#else 238return true; 239#endif 240 }(); 241return on && (head_dim == 128 || head_dim == 256 )&& n_rot == 64 ; 242} 243 244void native_rope_apply (const float * x ,float * out ,int rows ,int head_dim , 245int n_rot ,const RopeScaling & scaling ,const int * positions ,void * stream ) { 246if (!x || !out || !positions || !stream || rows < 1 || rows > 65535 || 247 (head_dim != 128 && head_dim != 256 )|| n_rot != 64 || 248rope_scaling_invalid (scaling )!= nullptr || 249reinterpret_cast < uintptr_t > (x ) %4 || reinterpret_cast < uintptr_t > (out ) %4 || 250reinterpret_cast < uintptr_t > (positions ) %4 ) { 251throw std::invalid_argument ("native RoPE requires aligned F32 rows, width 128/256, rotation 64, valid base/scaling and explicit stream" ); 252 } 253const size_t bytes = size_t (rows )* head_dim * sizeof (float ); 254if ((x != out && overlaps (x ,bytes ,out ,bytes ))|| 255overlaps (positions ,size_t (rows )* sizeof (int ),out ,bytes )|| 256overlaps (positions ,size_t (rows )* sizeof (int ),x ,bytes )) { 257throw std::invalid_argument ("native RoPE buffers partially overlap" ); 258 } 259// Match pinned host-side float powf before device fast powf/trigonometry. 260const float theta_scale = powf ((float )scaling .freq_base ,-2.0f /n_rot ); 261const RopeKernelArgs k = scaling .kernel_args (n_rot );// none: the identity constants 262const RopeTab rt = rope_table_for (scaling ); 263const unsigned threads = (x == out && n_rot == 64 && native_norm_rope_usable (head_dim ,n_rot )) ?32u :128u ; 264const dpct::dim3 grid ( 265threads == 32u ?1u :unsigned ((head_dim /2 + 127 ) /128 ),rows ); 266if (rt .cos != nullptr ) 267/* 268DPCT1049: The work-group size passed to the SYCL kernel may exceed 269the limit. To get the device limit, query 270info::device::max_work_group_size. Adjust the work-group size if needed. 271*/ 272 { 273auto exp_props = sycl::ext::oneapi::experimental::properties { 274 sycl::ext::oneapi::experimental::use_root_sync }; 275 276 strata::kprof::kp (strata::q_of (stream ),__FILE__ ,__func__ ,__LINE__ ) 277-> submit ([& ](sycl::handler & cgh ) { 278auto mrope_table_ct12 = mrope_table (); 279 280cgh .parallel_for < dpct_kernel_name < class apply_b955ef , 281dpct_kernel_scalar < true>>> ( 282 sycl::nd_range < 3 > (grid * sycl::range (1 ,1 ,threads ), 283 sycl::range (1 ,1 ,threads )), 284exp_props , [= ](sycl::nd_item < 3 > item_ct1 ) { 285apply < true> (x ,out ,rows ,head_dim ,n_rot ,theta_scale , 286k .freq_scale ,k .corr_low ,k .corr_high , 287k .ext_factor ,k .attn_factor ,positions , 288mrope_table_ct12 ,rt ); 289 }); 290 }); 291 }else 292/* 293DPCT1049: The work-group size passed to the SYCL kernel may exceed 294the limit. To get the device limit, query 295info::device::max_work_group_size. Adjust the work-group size if needed. 296*/ 297 { 298auto exp_props = sycl::ext::oneapi::experimental::properties { 299 sycl::ext::oneapi::experimental::use_root_sync }; 300 301 strata::kprof::kp (strata::q_of (stream ),__FILE__ ,__func__ ,__LINE__ ) 302-> submit ([& ](sycl::handler & cgh ) { 303auto mrope_table_ct12 = mrope_table (); 304 305cgh .parallel_for < dpct_kernel_name < class apply_b955ef , 306dpct_kernel_scalar < false>>> ( 307 sycl::nd_range < 3 > (grid * sycl::range (1 ,1 ,threads ), 308 sycl::range (1 ,1 ,threads )), 309exp_props , [= ](sycl::nd_item < 3 > item_ct1 ) { 310apply < false> (x ,out ,rows ,head_dim ,n_rot ,theta_scale , 311k .freq_scale ,k .corr_low ,k .corr_high , 312k .ext_factor ,k .attn_factor ,positions , 313mrope_table_ct12 ,rt ); 314 }); 315 }); 316 } 317/* 318DPCT1010: SYCL uses exceptions to report errors and does not use the 319error codes. The cudaGetLastError function call was replaced with 0. You 320need to rewrite this code. 321*/ 322const auto error = 0 ; 323/* 324DPCT1009: SYCL reports errors using exceptions and does not use error 325codes. Please replace the "get_error_string_dummy(...)" with a real 326error-handling function. 327*/ 328/* 329DPCT1001: The statement could not be removed. 330*/ 331/* 332DPCT1000: Error handling if-stmt was detected but could not be 333rewritten. 334*/ 335if (error != 3360 )throw std::runtime_error (dpct::get_error_string_dummy (error )); 337} 338 339void native_qsa_rms_norm_rope (const float * x ,int in_stride ,const float * gamma ,float * out , 340int rows ,int head_dim ,int n_rot ,float epsilon , 341const RopeScaling & scaling ,const int * positions ,void * stream ) { 342if (!x || !gamma || !out || !positions || !stream || rows < 1 || rows > 65535 || 343 (head_dim != 128 && head_dim != 256 )|| in_stride < head_dim || n_rot != 64 || 344 !std::isfinite (epsilon )|| epsilon < 0.0f || 345rope_scaling_invalid (scaling )!= nullptr || 346reinterpret_cast < uintptr_t > (x ) %4 || reinterpret_cast < uintptr_t > (gamma ) %4 || 347reinterpret_cast < uintptr_t > (out ) %4 || reinterpret_cast < uintptr_t > (positions ) %4 ) { 348throw std::invalid_argument ("native_qsa_rms_norm_rope: invalid arguments" ); 349 } 350const float theta_scale = powf ((float )scaling .freq_base ,-2.0f /n_rot ); 351const RopeKernelArgs k = scaling .kernel_args (n_rot ); 352const RopeTab rt = rope_table_for (scaling ); 353if (rt .cos != nullptr ) 354 { 355auto exp_props = sycl::ext::oneapi::experimental::properties { 356 sycl::ext::oneapi::experimental::use_root_sync }; 357 358 strata::kprof::kp (strata::q_of (stream ),__FILE__ ,__func__ ,__LINE__ ) 359-> submit ([& ](sycl::handler & cgh ) { 360auto mrope_table_ct14 = mrope_table (); 361 362cgh .parallel_for < dpct_kernel_name < class norm_rope_kernel_c8b2b8 , 363dpct_kernel_scalar < true>>> ( 364 sycl::nd_range < 3 > (sycl::range (1 ,1 ,unsigned (rows ))* 365 sycl::range (1 ,1 ,256 ), 366 sycl::range (1 ,1 ,256 )), 367exp_props , 368 [= ](sycl::nd_item < 3 > item_ct1 ) 369 [[sycl ::reqd_sub_group_size (32 )]] { 370norm_rope_kernel < true> ( 371x ,in_stride ,gamma ,out ,head_dim ,n_rot , 372epsilon ,theta_scale ,k .freq_scale ,k .corr_low , 373k .corr_high ,k .ext_factor ,k .attn_factor , 374positions ,mrope_table_ct14 ,rt ); 375 }); 376 }); 377 }else { 378auto exp_props = sycl::ext::oneapi::experimental::properties { 379 sycl::ext::oneapi::experimental::use_root_sync }; 380 381 strata::kprof::kp (strata::q_of (stream ),__FILE__ ,__func__ ,__LINE__ ) 382-> submit ([& ](sycl::handler & cgh ) { 383auto mrope_table_ct14 = mrope_table (); 384 385cgh .parallel_for < dpct_kernel_name < class norm_rope_kernel_f9c8ef , 386dpct_kernel_scalar < false>>> ( 387 sycl::nd_range < 3 > (sycl::range (1 ,1 ,unsigned (rows ))* 388 sycl::range (1 ,1 ,256 ), 389 sycl::range (1 ,1 ,256 )), 390exp_props , 391 [= ](sycl::nd_item < 3 > item_ct1 ) 392 [[sycl ::reqd_sub_group_size (32 )]] { 393norm_rope_kernel < false> ( 394x ,in_stride ,gamma ,out ,head_dim ,n_rot , 395epsilon ,theta_scale ,k .freq_scale ,k .corr_low , 396k .corr_high ,k .ext_factor ,k .attn_factor , 397positions ,mrope_table_ct14 ,rt ); 398 }); 399 }); 400 } 401/* 402DPCT1010: SYCL uses exceptions to report errors and does not use the 403error codes. The cudaGetLastError function call was replaced with 0. You 404need to rewrite this code. 405*/ 406const auto error = 0 ; 407/* 408DPCT1009: SYCL reports errors using exceptions and does not use error 409codes. Please replace the "get_error_string_dummy(...)" with a real 410error-handling function. 411*/ 412/* 413DPCT1001: The statement could not be removed. 414*/ 415/* 416DPCT1000: Error handling if-stmt was detected but could not be 417rewritten. 418*/ 419if (error != 4200 )throw std::runtime_error (dpct::get_error_string_dummy (error )); 421} 422}