okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
86bed1c92
main
1// src/kernels/cuda/gdn.cu - P2.S2: the gated delta-net's non-projection parts. 2// 3// See include/strata/kernels/gdn.hpp for the state layout (S, h_v, S) and for why the recurrence needs no 4// barrier at all: every line of it touches only one (j, h) column, so one thread owns a column end to end. 5#define DPCT_PROFILING_ENABLED 6#include <sycl/sycl.hpp> 7#include "strata/kprof.hpp" 8#include <dpct/dpct.hpp> 9#include "strata/sycl_queue.hpp" 10#include "strata/kernels/gdn.hpp" 11 12#include <cmath> 13#include <cstdio> 14#include <cstdlib> 15 16namespace strata::kernels { 17namespace { 18 19constexpr int JTHREADS = 32 ;///< threads along j, the state's fast axis 20/// Heads staged per block. **THIS IS A LATENCY-HIDING KNOB, NOT A CAPACITY ONE, AND IT WAS SET WRONG.** 21/// 22/// The kernel is one thread per `(h, j)` COLUMN of the state, so the thread count is fixed at 23/// `S * h_v` = 128 * 48 = **6,144** no matter how the work is packed - and `MAX_H` decides only how many of 24/// those columns share a block: 25/// 26/// MAX_H = 8 grid = (S/32, h_v/8) = (4, 6) = 24 blocks x 32 threads -> 1 warp on 24 of 48 SMs 27/// MAX_H = 1 grid = (S/32, h_v/1) = (4, 48) = 192 blocks x 32 threads -> 4 warps on every SM 28/// 29/// Each thread walks `i` in 0..S-1 TWICE per head with a strided global load each step, so it is entirely 30/// latency-bound: a warp that issues one 128-byte transaction and then waits ~600 cycles needs other warps to 31/// run meanwhile, and at 24 blocks there were none. Measured 0.2800 ms per GDN block - 10 ms of a 71.5 ms 32/// token, 14%, in a kernel touching 12.6 MB that a 643 GB/s card should do in 0.020 ms. 33/// 34/// The arithmetic does not change at all: the same columns are computed by the same code, in different blocks. 35constexpr int MAX_H = 1 ;///< heads staged in shared memory per block 36 37/// ggml_compute_softplus_f32: log1p(exp(x)), with the large-x branch that avoids overflow. 38__dpct_inline__ float softplus_f (float x ) { 39return x > 20.0f ?x : sycl::log1p (sycl::native::exp (x )); 40} 41__dpct_inline__ float sigmoid_f (float x ) { 42return 1.0f / (1.0f + sycl::native::exp (- x )); 43} 44 45/// One step of the recurrence. One thread per (h, j) column of the state. 46/// 47/// `ks`/`qs` stage `k[idx[h]]` and `q[idx[h]]` for the block's heads. Within a warp h is constant and j 48/// varies, so the staged row is read with a single broadcast - which is also why the GLOBAL loads of 49/// `q`/`k` are done once per block into shared instead of once per thread. 50__dpct_inline__ void 51gdn_step_kernel (float * __restrict__state ,const float * __restrict__q , 52const float * __restrict__k ,const float * __restrict__v , 53const float * __restrict__gate ,const float * __restrict__beta , 54float * __restrict__o ,int S ,int h_k ,int h_v ) { 55auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item < 3 > (); 56auto & ks = 57* sycl::ext::oneapi::group_local_memory_for_overwrite < float [MAX_H ][128 ]> ( 58 sycl::ext::oneapi::this_work_item::get_work_group < 3 > ()); 59auto & qs = 60* sycl::ext::oneapi::group_local_memory_for_overwrite < float [MAX_H ][128 ]> ( 61 sycl::ext::oneapi::this_work_item::get_work_group < 3 > ()); 62auto & dec_s = 63* sycl::ext::oneapi::group_local_memory_for_overwrite < float [MAX_H ]> ( 64 sycl::ext::oneapi::this_work_item::get_work_group < 3 > ()); 65auto & beta_s = 66* sycl::ext::oneapi::group_local_memory_for_overwrite < float [MAX_H ]> ( 67 sycl::ext::oneapi::this_work_item::get_work_group < 3 > ()); 68 69const int h0 = item_ct1 .get_group (1 )* MAX_H ; 70const int nh = sycl::min (MAX_H ,h_v - h0 ); 71const int j = item_ct1 .get_group (2 )* JTHREADS + item_ct1 .get_local_id (2 ); 72 73// stage this block's q/k rows and its per-head scalars 74for (int hi = 0 ;hi < nh ;++ hi ) { 75const int h = h0 + hi ; 76const int src = h %h_k ;// MODULO head pairing 77#pragma unroll 78for (int i = item_ct1 .get_local_id (2 );i < S ;i += JTHREADS ) { 79ks [hi ][i ]= k [src * S + i ]; 80qs [hi ][i ]= q [src * S + i ]; 81 } 82if (item_ct1 .get_local_id (2 )== 0 ) { 83dec_s [hi ]= sycl::native::exp (gate [h ]); 84beta_s [hi ]= beta [h ]; 85 } 86 } 87/* 88DPCT1065: Consider replacing sycl::nd_item::barrier() with 89sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better 90performance if there is no access to global memory. 91*/ 92item_ct1 .barrier (); 93if (j >=S )return ; 94 95for (int hi = 0 ;hi < nh ;++ hi ) { 96const int h = h0 + hi ; 97const float dec = dec_s [hi ],b = beta_s [hi ]; 98float * col = state + (size_t )h * S + j ;// (S, h_v, S) with j fastest 99const size_t stride = (size_t )h_v * S ; 100 101// pass 1: decay the state and contract it against k. Decay BEFORE the update - PROPERTY 5. 102float sk = 0.0f ; 103for (int i = 0 ;i < S ;++ i ) { 104const float s = col [(size_t )i * stride ]* dec ; 105col [(size_t )i * stride ]= s ; 106sk += s * ks [hi ][i ]; 107 } 108const float d = (v [(size_t )h * S + j ]- sk )* b ; 109// pass 2: the rank-1 update, then read out against q using the UPDATED state 110float dot = 0.0f ; 111for (int i = 0 ;i < S ;++ i ) { 112const float s = col [(size_t )i * stride ]+ ks [hi ][i ]* d ; 113col [(size_t )i * stride ]= s ; 114dot += s * qs [hi ][i ]; 115 } 116o [(size_t )h * S + j ]= dot ; 117 } 118} 119 120/// `ggml_ssm_conv`: out[c] = sum_i inp[i][c] * kW[c*d_conv + i], inp = [conv_state | x], and the state slides. 121/// One thread per channel; d_conv is 4, so the serial work per thread is a 4-tap dot and an unrolled shift. 122__dpct_inline__ void gdn_conv_kernel (float * __restrict__cs , 123const float * __restrict__x , 124const float * __restrict__kW , 125float * __restrict__out ,int C ,int dc ) { 126auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item < 3 > (); 127const int c = item_ct1 .get_group (2 )* item_ct1 .get_local_range (2 )+ 128item_ct1 .get_local_id (2 ); 129if (c >=C )return ; 130float * st = cs + (size_t )c * (dc - 1 ); 131const float * w = kW + (size_t )c * dc ; 132float acc = 0.0f ; 133#pragma unroll 134for (int i = 0 ;i < dc - 1 ;++ i )acc += 135st [i ]* w [i ];// kernel[0] reads the OLDEST state row 136acc += x [c ]* w [dc - 1 ];// the new input lands in the LAST tap 137out [c ]= acc ; 138#pragma unroll 139for (int i = 0 ;i < dc - 2 ;++ i ) 140st [i ]= st [i + 1 ];// slide: drop the oldest, append the newest 141st [dc - 2 ]= x [c ]; 142} 143 144/// `build_gdn_l2_norm`, one warp per row: x / sqrt(sum(x^2) + eps) over the last axis. 145/// 146/// The sum is accumulated in DOUBLE, as `ref/gdn.py` does (`l2_norm(q.astype(np.float64), eps)`), because the 147/// reference deliberately computes this one in float64 and then casts - so matching its precision is part of 148/// transcribing it. 149__dpct_inline__ void gdn_l2_kernel (float * __restrict__x ,int cols ,float eps ) { 150auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item < 3 > (); 151const int row = item_ct1 .get_group (2 ); 152float * p = x + (size_t )row * cols ; 153double acc = 0.0 ; 154#pragma unroll 155for (int i = item_ct1 .get_local_id (2 );i < cols ; 156i += item_ct1 .get_local_range (2 ))acc += (double )p [i ]* (double )p [i ]; 157// warp reduction 158/* 159DPCT1108: '__shfl_down_sync' was migrated with the experimental feature 160masked sub_group function which may not be supported by all compilers or 161runtimes. You may need to adjust the code. 162*/ 163#pragma unroll 164for (int off = 16 ;off > 0 ;off >>=1 )acc += 165 dpct::experimental::shift_sub_group_left ( 1660xFFFFFFFFu , sycl::ext::oneapi::this_work_item::get_sub_group (), 167acc ,off ); 168auto & ssum = * sycl::ext::oneapi::group_local_memory_for_overwrite < double > ( 169 sycl::ext::oneapi::this_work_item::get_work_group < 3 > ()); 170if (item_ct1 .get_local_id (2 )== 0 )ssum = acc ; 171/* 172DPCT1065: Consider replacing sycl::nd_item::barrier() with 173sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better 174performance if there is no access to global memory. 175*/ 176item_ct1 .barrier (); 177const float inv = (float )(1.0 / sycl::sqrt (ssum + (double )eps )); 178#pragma unroll 179for (int i = item_ct1 .get_local_id (2 );i < cols ; 180i += item_ct1 .get_local_range (2 ))p [i ] *=inv ; 181} 182 183/// y = rms_norm(o, eps) * ssm_norm * sigmoid(z), one warp per head, norm over that head's S values. 184__dpct_inline__ void gdn_out_norm_kernel (const float * __restrict__o , 185const float * __restrict__z , 186const float * __restrict__ssm_norm , 187float * __restrict__y ,int S , 188float eps ) { 189auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item < 3 > (); 190const int h = item_ct1 .get_group (2 ); 191const float * po = o + (size_t )h * S ; 192const float * pz = z + (size_t )h * S ; 193float * py = y + (size_t )h * S ; 194double acc = 0.0 ; 195#pragma unroll 196for (int i = item_ct1 .get_local_id (2 );i < S ; 197i += item_ct1 .get_local_range (2 ))acc += (double )po [i ]* (double )po [i ]; 198/* 199DPCT1108: '__shfl_down_sync' was migrated with the experimental feature 200masked sub_group function which may not be supported by all compilers or 201runtimes. You may need to adjust the code. 202*/ 203#pragma unroll 204for (int off = 16 ;off > 0 ;off >>=1 )acc += 205 dpct::experimental::shift_sub_group_left ( 2060xFFFFFFFFu , sycl::ext::oneapi::this_work_item::get_sub_group (), 207acc ,off ); 208auto & ssum = * sycl::ext::oneapi::group_local_memory_for_overwrite < double > ( 209 sycl::ext::oneapi::this_work_item::get_work_group < 3 > ()); 210if (item_ct1 .get_local_id (2 )== 0 )ssum = acc ; 211item_ct1 .barrier (sycl::access::fence_space::local_space ); 212const float inv = (float )(1.0 / sycl::sqrt (ssum / (double )S + (double )eps )); 213#pragma unroll 214for (int i = item_ct1 .get_local_id (2 );i < S ; 215i += item_ct1 .get_local_range (2 )) 216py [i ]= po [i ]* inv * ssm_norm [i ]* sigmoid_f (pz [i ]); 217} 218 219}// namespace 220 221void gdn_step (float * state ,const float * q ,const float * k ,const float * v , 222const float * gate ,const float * beta ,float * o , 223const GdnShapes & s ,void * stream )try { 224if (s .S <=0 || s .h_k <=0 || s .h_v <=0 )return ; 225if (s .S > 128 ) { 226 std::fprintf (stderr ,"gdn_step: S = %lld exceeds the staged 128 (`ks`/`qs` are [8][128])\n" , 227 (long long )s .S ); 228 std::exit (1 ); 229 } 230const dpct::dim3 grid ((unsigned )((s .S + JTHREADS - 1 ) /JTHREADS ), 231 (unsigned )((s .h_v + MAX_H - 1 ) /MAX_H )); 232 { 233auto exp_props = sycl::ext::oneapi::experimental::properties { 234 sycl::ext::oneapi::experimental::use_root_sync }; 235 236 strata::kprof::kp (strata::q_of (stream ),__FILE__ ,__func__ ,__LINE__ ) 237-> template parallel_for < dpct_kernel_name < class gdn_step_kernel_34b62e >> ( 238 sycl::nd_range < 3 > (grid * sycl::range (1 ,1 ,JTHREADS ), 239 sycl::range (1 ,1 ,JTHREADS )), 240exp_props , [= ](sycl::nd_item < 3 > item_ct1 ) { 241gdn_step_kernel (state ,q ,k ,v ,gate ,beta ,o , (int )s .S , 242 (int )s .h_k , (int )s .h_v ); 243 }); 244 } 245if (stream == nullptr ) { 246const dpct::err0 e = DPCT_CHECK_ERROR ( 247 dpct::get_current_device ().queues_wait_and_throw ()); 248 } 249} 250catch (sycl::exception const & exc ) { 251 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 252 <<", line:" <<__LINE__ << std::endl ; 253 std::exit (1 ); 254} 255 256void gdn_conv_step (float * conv_state ,const float * x ,const float * kW , 257float * out ,int64_t channels ,int64_t d_conv , 258void * stream )try { 259if (channels <=0 || d_conv < 1 )return ; 260const int blocks = (int ) ((channels + 255 ) /256 ); 261 { 262auto exp_props = sycl::ext::oneapi::experimental::properties { 263 sycl::ext::oneapi::experimental::use_root_sync }; 264 265 strata::kprof::kp (strata::q_of (stream ),__FILE__ ,__func__ ,__LINE__ ) 266-> template parallel_for < dpct_kernel_name < class gdn_conv_kernel_b12e73 >> ( 267 sycl::nd_range < 3 > (sycl::range (1 ,1 ,blocks )* 268 sycl::range (1 ,1 ,256 ), 269 sycl::range (1 ,1 ,256 )), 270exp_props , [= ](sycl::nd_item < 3 > item_ct1 ) { 271gdn_conv_kernel (conv_state ,x ,kW ,out , (int )channels , 272 (int )d_conv ); 273 }); 274 } 275if (stream == nullptr ) { 276const dpct::err0 e = DPCT_CHECK_ERROR ( 277 dpct::get_current_device ().queues_wait_and_throw ()); 278 } 279} 280catch (sycl::exception const & exc ) { 281 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 282 <<", line:" <<__LINE__ << std::endl ; 283 std::exit (1 ); 284} 285 286void gdn_l2_norm (float * x ,int64_t rows ,int64_t cols ,float eps , 287void * stream )try { 288if (rows <=0 || cols <=0 )return ; 289if (cols > 1024 ) { 290 std::fprintf (stderr ,"gdn_l2_norm: cols = %lld exceeds the 1024-wide warp reduction\n" , (long long )cols ); 291 std::exit (1 ); 292 } 293 { 294auto exp_props = sycl::ext::oneapi::experimental::properties { 295 sycl::ext::oneapi::experimental::use_root_sync }; 296 dpct::has_capability_or_fail ( 297 strata::q_of (stream )-> get_device (), 298 {sycl::aspect::fp64 }); 299 300 strata::kprof::kp (strata::q_of (stream ),__FILE__ ,__func__ ,__LINE__ ) 301-> template parallel_for < dpct_kernel_name < class gdn_l2_kernel_fcfb3d >> ( 302 sycl::nd_range < 3 > (sycl::range (1 ,1 , (unsigned )rows )* 303 sycl::range (1 ,1 ,32 ), 304 sycl::range (1 ,1 ,32 )), 305exp_props , 306 [= ](sycl::nd_item < 3 > item_ct1 ) 307 [[sycl ::reqd_sub_group_size (32 )]] { 308gdn_l2_kernel (x , (int )cols ,eps ); 309 }); 310 } 311if (stream == nullptr ) { 312const dpct::err0 e = DPCT_CHECK_ERROR ( 313 dpct::get_current_device ().queues_wait_and_throw ()); 314 } 315} 316catch (sycl::exception const & exc ) { 317 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 318 <<", line:" <<__LINE__ << std::endl ; 319 std::exit (1 ); 320} 321 322/// `beta = sigmoid(beta)`, in place, over the `h_v` per-head scalars. 323/// 324/// **THIS IS `build_layer_attn_linear` L889, AND LEAVING IT OUT WAS THE C1 BUG.** The reference computes 325/// `beta = ggml_sigmoid(ssm_beta @ cur)` and hands the RESULT to the delta net; `gdn_step_kernel` is documented 326/// as `d[h,j] = (v[h,j] - sk[h,j]) * beta[h]` and applies no sigmoid of its own, so the layer glue owes it one. 327/// The engine passed the raw pre-activation, which is unbounded and signed - the delta-net write strength then 328/// stops being a fraction and the whole recurrence is wrong from layer 0. 329/// 330/// **IT SURVIVED `gdn_parity` BECAUSE THAT TEST SUPPLIES ITS OWN `beta`.** The kernel was always right; only 331/// the glue between the projection and the kernel was wrong, and `ref/gdn.py` (`beta = sigmoid(wbeta @ x)`) and 332/// `ref/model.py` (`beta = G.sigmoid(proj(...))`) both get it right - so the two transcriptions agreed with 333/// each other and neither was ever compared against the C++ that actually runs. 334__dpct_inline__ void gdn_beta_gate_kernel (float * __restrict__beta ,int n ) { 335auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item < 3 > (); 336const int i = item_ct1 .get_group (2 )* item_ct1 .get_local_range (2 )+ 337item_ct1 .get_local_id (2 ); 338if (i < n )beta [i ]= sigmoid_f (beta [i ]); 339} 340 341void gdn_beta_gate (float * beta ,int64_t h_v ,void * stream )try { 342if (beta == nullptr || h_v <=0 )return ; 343const int n = (int )h_v ; 344 { 345auto exp_props = sycl::ext::oneapi::experimental::properties { 346 sycl::ext::oneapi::experimental::use_root_sync }; 347 348 strata::kprof::kp (strata::q_of (stream ),__FILE__ ,__func__ ,__LINE__ ) 349-> template parallel_for < dpct_kernel_name < class gdn_beta_gate_kernel_e2ab3e >> ( 350 sycl::nd_range < 3 > ( 351 sycl::range (1 ,1 , (unsigned )((n + 127 ) /128 ))* 352 sycl::range (1 ,1 ,128 ), 353 sycl::range (1 ,1 ,128 )), 354exp_props , [= ](sycl::nd_item < 3 > item_ct1 ) { 355gdn_beta_gate_kernel (beta ,n ); 356 }); 357 } 358if (stream == nullptr ) { 359const dpct::err0 e = DPCT_CHECK_ERROR ( 360 dpct::get_current_device ().queues_wait_and_throw ()); 361 } 362} 363catch (sycl::exception const & exc ) { 364 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 365 <<", line:" <<__LINE__ << std::endl ; 366 std::exit (1 ); 367} 368 369void gdn_out_norm (const float * o ,const float * z ,const float * ssm_norm , 370float * y ,int64_t h_v ,int64_t S ,float eps , 371void * stream )try { 372if (h_v <=0 || S <=0 )return ; 373 { 374auto exp_props = sycl::ext::oneapi::experimental::properties { 375 sycl::ext::oneapi::experimental::use_root_sync }; 376 dpct::has_capability_or_fail ( 377 strata::q_of (stream )-> get_device (), 378 {sycl::aspect::fp64 }); 379 380 strata::kprof::kp (strata::q_of (stream ),__FILE__ ,__func__ ,__LINE__ ) 381-> template parallel_for < dpct_kernel_name < class gdn_out_norm_kernel_9883e0 >> ( 382 sycl::nd_range < 3 > (sycl::range (1 ,1 , (unsigned )h_v )* 383 sycl::range (1 ,1 ,32 ), 384 sycl::range (1 ,1 ,32 )), 385exp_props , 386 [= ](sycl::nd_item < 3 > item_ct1 ) 387 [[sycl ::reqd_sub_group_size (32 )]] { 388gdn_out_norm_kernel (o ,z ,ssm_norm ,y , (int )S ,eps ); 389 }); 390 } 391if (stream == nullptr ) { 392const dpct::err0 e = DPCT_CHECK_ERROR ( 393 dpct::get_current_device ().queues_wait_and_throw ()); 394 } 395} 396catch (sycl::exception const & exc ) { 397 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 398 <<", line:" <<__LINE__ << std::endl ; 399 std::exit (1 ); 400} 401 402}// namespace strata::kernels