okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
86bed1c92
main
1// src/kernels/cuda/rope.cu - P2.S2: NEOX partial RoPE. 2// 3// Semantics from `ref/qsa.py` (`rope_freqs` + `rope_neox`), which `bench/micro/rope_xcheck` validates against 4// the oracle: 5// 6// inv[i] = theta ** (-2i / n_rot) i in [0, n_rot/2) 7// ang = pos * inv 8// cos, sin = cos(ang), sin(ang) 9// out[:half] = a*cos - b*sin a = x[:half], b = x[half:n_rot] 10// out[half:n_rot] = a*sin + b*cos 11// 12// THE PAIRING IS NEOX - (i, i + n_rot/2), NOT the adjacent pair (2i, 2i+1). `ggml.h` writes NEOX 13// n_dims=8 as [ccccssss]; the adjacent-pair ("NORMAL") ordering is the other common convention and choosing 14// wrongly rotates the wrong dimensions together, which produces correctly-shaped output with scrambled 15// content. It is also PARTIAL: only the first n_rot of head_dim are touched, here 64 of 256. 16// 17// WHY THE TABLE IS BUILT ON THE HOST. The reference computes the frequencies in FLOAT64 (`theta ** (...)` 18// on a float64 arange, cos/sin in float64). Reproducing that on device means double-precision pow and cos, 19// which are slow on a consumer GPU and - more to the point - not guaranteed to agree with the host's libm. 20// Building the table once on the host and passing it in makes the TABLE exactly the reference's values and 21// leaves the kernel a pure rotation, so each half can be checked tightly instead of both halves sharing one 22// loose tolerance. The engine wants a cached table anyway: it is per (n_rot, theta, position), not per token. 23// 24// THE SCALED TABLE IS THE SAME IDEA WITH MORE MATH IN THE HOST LOOP. Linear rescales the angle by 25// `freq_scale`; YaRN blends extrapolation and interpolation along the pairs (ggml's `rope_yarn`) and folds 26// the mscale magnitude correction into the same cos/sin values. All of it float64, in the reference's 27// order, so `rope_parity` can hold every variant to a bit-exact float64 transcription of the same spec. 28#define DPCT_PROFILING_ENABLED 29#include <sycl/sycl.hpp> 30#include "strata/kprof.hpp" 31#include <dpct/dpct.hpp> 32#include "strata/sycl_queue.hpp" 33#include "strata/kernels/rope.hpp" 34#include "strata/kernels/mrope.hpp" 35 36#include <cmath> 37#include <cstdio> 38#include <cstdlib> 39 40namespace strata::kernels { 41 42namespace { 43// The process's rope config (rope_scaling.hpp). One writer - the engine's startup thread, before 44// session_init builds any table or captures any graph - and readers after it. 45RopeScaling g_rope_scaling ; 46}// namespace 47 48void rope_scaling_set (const RopeScaling & scaling ) {g_rope_scaling = scaling ; } 49const RopeScaling & rope_scaling () {return g_rope_scaling ; } 50 51void build_rope_table (int n_rot ,double theta ,int max_pos ,float * cos_tab ,float * sin_tab ) { 52const int half = n_rot /2 ; 53for (int p = 0 ;p < max_pos ;++ p ) { 54for (int i = 0 ;i < half ;++ i ) { 55// float64 throughout, in the reference's order: inv, then ang, then cos/sin 56const double inv = std::pow (theta ,-2.0 * (double )i / (double )n_rot ); 57const double ang = (double )p * inv ; 58cos_tab [(size_t )p * half + i ]= (float ) std::cos (ang ); 59sin_tab [(size_t )p * half + i ]= (float ) std::sin (ang ); 60 } 61 } 62} 63 64void build_rope_table (int n_rot ,const RopeScaling & sc ,int max_pos ,float * cos_tab ,float * sin_tab ) { 65if (sc .type == RopeScalingType ::None ) { 66build_rope_table (n_rot ,sc .freq_base ,max_pos ,cos_tab ,sin_tab );// the original loop, verbatim 67return ; 68 } 69const int half = n_rot /2 ; 70const double fs = sc .freq_scale (); 71const double ms = sc .mscale (); 72double cd [2 ]; 73sc .corr_dims (n_rot ,cd ); 74const bool correct = sc .ext_factor != 0 ;// ggml: the correction rides on ext_factor, not the type 75for (int p = 0 ;p < max_pos ;++ p ) { 76for (int i = 0 ;i < half ;++ i ) { 77const double inv = std::pow (sc .freq_base ,-2.0 * (double )i / (double )n_rot ); 78const double extrap = (double )p * inv ;// the trained angle, ggml's theta_extrap 79const double interp = fs * extrap ;// ggml's theta_interp 80double ang = interp ; 81if (correct ) { 82const double ramp = (double )rope_yarn_ramp ((float )cd [0 ], (float )cd [1 ],i )* sc .ext_factor ; 83ang = interp * (1.0 - ramp )+ extrap * ramp ; 84 } 85cos_tab [(size_t )p * half + i ]= (float ) (std::cos (ang )* ms ); 86sin_tab [(size_t )p * half + i ]= (float ) (std::sin (ang )* ms ); 87 } 88 } 89} 90 91namespace { 92 93// ONE THREAD PER ROW, not per (row, pair). The first version had one thread per pair and did the tail copy 94// with hreadIdx.x strided loops - so up to 32 threads wrote into the SAME row, with no barrier between the 95// copy and the rotation, and a thread's copy of orow[i] could land AFTER another thread had rotated it. A 96// race that silently writes the unrotated value is worse than a wrong answer: it is intermittent. 97// 98// A row is head_dim floats (256 here) and there are batch x heads of them, so one thread per row is a 99// handful of threads for a token and removes the ordering question entirely rather than synchronising it. 100__dpct_inline__ void rope_neox_kernel (const float * __restrict__x , 101float * __restrict__out ,long long rows , 102int head_dim ,int n_rot , 103const float * __restrict__cos_tab , 104const float * __restrict__sin_tab , 105const int * __restrict__pos , 106const int32_t * __restrict__mtab ) { 107auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item < 3 > (); 108const long long r = 109 (long long )item_ct1 .get_group (2 )* item_ct1 .get_local_range (2 )+ 110item_ct1 .get_local_id (2 ); 111if (r >=rows )return ; 112const int half = n_rot /2 ; 113const float * xr = x + r * head_dim ; 114float * orow = out + r * head_dim ; 115 116#pragma unroll 117for (int d = n_rot ;d < head_dim ;++ d ) 118orow [d ]= xr [d ];// the PARTIAL rotation's untouched tail 119for (int i = 0 ;i < half ;++ i ) { 120const size_t toff = (size_t )mrope_pos (mtab ,pos [r ],i )* half ;// the image path's per-pair position 121// THE PAIRING AND THE SIGNS COME FROM `rope_neox_pair`, shared with the indexer's pooling kernel. 122rope_neox_pair (xr [i ],xr [half + i ],cos_tab [toff + i ],sin_tab [toff + i ],orow [i ],orow [half + i ]); 123 } 124} 125 126}// namespace 127 128void rope_neox_apply (const float * x ,float * out ,int64_t rows ,int head_dim ,int n_rot ,const float * cos_tab , 129const float * sin_tab ,const int * pos ,void * stream ) { 130if (rows <=0 || n_rot <=0 )return ; 131if (n_rot %2 != 0 || n_rot > head_dim ) { 132 std::fprintf (stderr ,"rope_neox_apply: n_rot %d must be even and <= head_dim %d\n" ,n_rot ,head_dim ); 133 std::exit (1 ); 134 } 135const int threads = 128 ; 136const unsigned grid = (unsigned ) ((rows + threads - 1 ) /threads ); 137 { 138auto exp_props = sycl::ext::oneapi::experimental::properties { 139 sycl::ext::oneapi::experimental::use_root_sync }; 140 141 strata::kprof::kp (strata::q_of (stream ),__FILE__ ,__func__ ,__LINE__ ) 142-> submit ([& ](sycl::handler & cgh ) { 143auto mrope_table_ct8 = mrope_table (); 144 145cgh .parallel_for < 146dpct_kernel_name < class rope_neox_kernel_e291c2 >> ( 147 sycl::nd_range < 3 > (sycl::range (1 ,1 ,grid )* 148 sycl::range (1 ,1 ,threads ), 149 sycl::range (1 ,1 ,threads )), 150exp_props , [= ](sycl::nd_item < 3 > item_ct1 ) { 151rope_neox_kernel (x ,out ,rows ,head_dim ,n_rot ,cos_tab , 152sin_tab ,pos ,mrope_table_ct8 ); 153 }); 154 }); 155 } 156/* 157DPCT1010: SYCL uses exceptions to report errors and does not use the 158error codes. The cudaGetLastError function call was replaced with 0. You 159need to rewrite this code. 160*/ 161const dpct::err0 e = 0 ; 162 163if (stream == nullptr ) dpct::get_current_device ().queues_wait_and_throw (); 164} 165 166}// namespace strata::kernels