okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
86bed1c92
main
1// Adapted from llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d: 2// ggml/src/ggml-cuda/{norm.cu,common.cuh,unary.cu,unary.cuh,ssm-conv.cu,scale.cu}. 3// Compile with --use_fast_math, as the pinned backend does. 4// 5// MIT License 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_gdn_preprocess.hpp" 31#include <cmath> 32#include <cstddef> 33#include <cstdint> 34#include <initializer_list> 35#include <stdexcept> 36 37namespace strata::kernels { 38namespace { 39constexpr int S = 128 ; 40 41__dpct_inline__ float warp_sum (float value ) { 42#pragma unroll 43for (int offset = 16 ;offset > 0 ;offset >>=1 ) 44/* 45DPCT1108: '__shfl_xor_sync' was migrated with the experimental 46feature masked sub_group function which may not be supported by all 47compilers or runtimes. You may need to adjust the code. 48*/ 49value += dpct::experimental::permute_sub_group_by_xor ( 500xffffffffu , sycl::ext::oneapi::this_work_item::get_sub_group (), 51value ,offset ); 52return value ; 53} 54__dpct_inline__ float norm_sum (float value ,float * sums ) { 55auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item < 3 > (); 56const int lane = item_ct1 .get_local_id (2 ) %32 ; 57value = warp_sum (value ); 58if (lane == 0 )sums [item_ct1 .get_local_id (2 ) /32 ]= value ; 59/* 60DPCT1065: Consider replacing sycl::nd_item::barrier() with 61sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better 62performance if there is no access to global memory. 63*/ 64item_ct1 .barrier (); 65value = lane < 8 ?sums [lane ] :0.0f ; 66return warp_sum (value ); 67} 68__dpct_inline__ float sigmoid (float value ) { 69return 1.0f / (1.0f + sycl::native::exp (- value )); 70} 71 72__dpct_inline__ void conv_silu (float * __restrict__history , 73const float * __restrict__input , 74const float * __restrict__weights , 75float * __restrict__raw_output , 76float * __restrict__silu_output ,int channels ) { 77auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item < 3 > (); 78const int c = item_ct1 .get_group (2 )* item_ct1 .get_local_range (2 )+ 79item_ct1 .get_local_id (2 ); 80if (c >=channels )return ; 81float values [4 ]= {history [c * 3 ],history [c * 3 + 1 ],history [c * 3 + 2 ],input [c ]}; 82float sum = 0.0f ; 83#pragma unroll 84for (int tap = 0 ;tap < 4 ;++ tap )sum += values [tap ]* weights [c * 4 + tap ]; 85// The native SSM kernel adds its zero bias even when there is no bias input. 86/* 87DPCT1013: The rounding mode could not be specified and the generated 88code may have different accuracy than the original code. Verify the 89correctness. SYCL math built-in function rounding mode is aligned with 90OpenCL C 1.2 standard. 91*/ 92sum = sum + 0.0f ; 93raw_output [c ]= sum ; 94silu_output [c ]= sum / (1.0f + sycl::native::exp (- sum )); 95#pragma unroll 96for (int tap = 0 ;tap < 3 ;++ tap )history [c * 3 + tap ]= values [tap + 1 ]; 97} 98 99__dpct_inline__ void l2_norm (float * input ,float epsilon ,float scale_after ) { 100auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item < 3 > (); 101const int col = item_ct1 .get_local_id (2 ); 102input += size_t (item_ct1 .get_group (2 ))* S ; 103const float value = col < S ?input [col ] :0.0f ; 104float partial = 0.0f ; 105if (col < S )partial += value * value ; 106auto & sums = 107* sycl::ext::oneapi::group_local_memory_for_overwrite < float [32 ]> ( 108 sycl::ext::oneapi::this_work_item::get_work_group < 3 > ()); 109partial = norm_sum (partial ,sums ); 110const float scale = sycl::rsqrt (partial /S + epsilon ); 111if (col < S ) { 112// Preserve the FP32 store boundary between RMSNorm and ggml_scale. 113/* 114DPCT1013: The rounding mode could not be specified and the generated 115code may have different accuracy than the original code. Verify the 116correctness. SYCL math built-in function rounding mode is aligned with 117OpenCL C 1.2 standard. 118*/ 119const float normalized = scale * value ; 120/* 121DPCT1013: The rounding mode could not be specified and the generated 122code may have different accuracy than the original code. Verify the 123correctness. SYCL math built-in function rounding mode is aligned with 124OpenCL C 1.2 standard. 125*/ 126input [col ]= sycl::fma (normalized ,scale_after ,0.0f ); 127 } 128} 129 130__dpct_inline__ void beta_sigmoid (float * beta ,int count ) { 131auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item < 3 > (); 132const int i = item_ct1 .get_group (2 )* item_ct1 .get_local_range (2 )+ 133item_ct1 .get_local_id (2 ); 134if (i < count )beta [i ]= sigmoid (beta [i ]); 135} 136__dpct_inline__ void gate_softplus (const float * __restrict__alpha , 137const float * __restrict__dt , 138const float * __restrict__ssm_a , 139float * __restrict__gate ,int count ) { 140auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item < 3 > (); 141const int i = item_ct1 .get_group (2 )* item_ct1 .get_local_range (2 )+ 142item_ct1 .get_local_id (2 ); 143if (i >=count )return ; 144/* 145DPCT1013: The rounding mode could not be specified and the generated 146code may have different accuracy than the original code. Verify the 147correctness. SYCL math built-in function rounding mode is aligned with 148OpenCL C 1.2 standard. 149*/ 150const float value = alpha [i ]+ dt [i ]; 151const float softplus = value > 20.0f 152 ?value 153 : sycl::log1p (sycl::native::exp ( 154value ));// 1 + e^v loses e^v below ~1e-7 155gate [i ]= softplus * ssm_a [i ]; 156} 157 158__dpct_inline__ void out_norm (const float * __restrict__input , 159const float * __restrict__z , 160const float * __restrict__gamma , 161float * __restrict__output ,float epsilon ) { 162auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item < 3 > (); 163const int col = item_ct1 .get_local_id (2 ); 164const size_t offset = size_t (item_ct1 .get_group (2 ))* S ; 165const float value = col < S ?input [offset + col ] :0.0f ; 166float partial = 0.0f ; 167if (col < S )partial += value * value ; 168auto & sums = 169* sycl::ext::oneapi::group_local_memory_for_overwrite < float [32 ]> ( 170 sycl::ext::oneapi::this_work_item::get_work_group < 3 > ()); 171partial = norm_sum (partial ,sums ); 172const float scale = sycl::rsqrt (partial /S + epsilon ); 173if (col < S ) { 174// RMSNorm+gamma is one pinned fused operator, followed by sigmoid*mul. 175/* 176DPCT1013: The rounding mode could not be specified and the generated 177code may have different accuracy than the original code. Verify the 178correctness. SYCL math built-in function rounding mode is aligned with 179OpenCL C 1.2 standard. 180*/ 181const float weighted = scale * value * gamma [col ]; 182output [offset + col ]= weighted * sigmoid (z [offset + col ]); 183 } 184} 185 186struct Span {const void * pointer ;size_t bytes ; }; 187void valid (Span span ) { 188const auto address = reinterpret_cast < uintptr_t > (span .pointer ); 189if (!span .pointer || address %sizeof (float )|| span .bytes > UINTPTR_MAX - address ) 190throw std::invalid_argument ("native GDN preprocessing requires aligned nonnull valid spans" ); 191} 192void disjoint (Span a ,Span b ) { 193const auto ap = reinterpret_cast < uintptr_t > (a .pointer ),bp = reinterpret_cast < uintptr_t > (b .pointer ); 194if (ap < bp + b .bytes && bp < ap + a .bytes ) 195throw std::invalid_argument ("native GDN preprocessing requires disjoint writable spans" ); 196} 197void count_and_stream (int64_t count ,void * stream ) { 198if (!stream || count <=0 || count > 65535 ) 199throw std::invalid_argument ("native GDN preprocessing requires a stream and count in [1,65535]" ); 200} 201void norm_geometry (int64_t rows ,int64_t cols ,float epsilon ,void * stream ) { 202count_and_stream (rows ,stream ); 203if (cols != S || !std::isfinite (epsilon )|| epsilon < 0.0f ) 204throw std::invalid_argument ("native GDN norm requires width 128 and finite nonnegative epsilon" ); 205} 206void check_launch () { 207/* 208DPCT1010: SYCL uses exceptions to report errors and does not use the 209error codes. The cudaGetLastError function call was replaced with 0. You 210need to rewrite this code. 211*/ 212const auto error = 0 ; 213/* 214DPCT1009: SYCL reports errors using exceptions and does not use error 215codes. Please replace the "get_error_string_dummy(...)" with a real 216error-handling function. 217*/ 218/* 219DPCT1001: The statement could not be removed. 220*/ 221/* 222DPCT1000: Error handling if-stmt was detected but could not be 223rewritten. 224*/ 225if (error != 2260 )throw std::runtime_error (dpct::get_error_string_dummy (error )); 227} 228} 229 230void native_gdn_conv_silu (float * history ,const float * input ,const float * weights , 231float * raw_output ,float * silu_output ,int64_t channels , 232int64_t d_conv ,void * stream ) { 233count_and_stream (channels ,stream ); 234if (d_conv != 4 )throw std::invalid_argument ("native GDN convolution requires four taps" ); 235const size_t bytes = size_t (channels )* sizeof (float ); 236const Span writable []= {{history ,3 * bytes }, {raw_output ,bytes }, {silu_output ,bytes }}; 237const Span inputs []= {{input ,bytes }, {weights ,4 * bytes }}; 238for (auto span :writable )valid (span ); 239for (auto span :inputs )valid (span ); 240for (int i = 0 ;i < 3 ;++ i ) { 241for (int j = 0 ;j < i ;++ j )disjoint (writable [i ],writable [j ]); 242for (auto span :inputs )disjoint (writable [i ],span ); 243 } 244 { 245auto exp_props = sycl::ext::oneapi::experimental::properties { 246 sycl::ext::oneapi::experimental::use_root_sync }; 247 248 strata::kprof::kp (strata::q_of (stream ),__FILE__ ,__func__ ,__LINE__ ) 249-> template parallel_for < dpct_kernel_name < class conv_silu_1ba4e6 >> ( 250 sycl::nd_range < 3 > ( 251 sycl::range (1 ,1 ,unsigned ((channels + 255 ) /256 ))* 252 sycl::range (1 ,1 ,256 ), 253 sycl::range (1 ,1 ,256 )), 254exp_props , [= ](sycl::nd_item < 3 > item_ct1 ) { 255conv_silu (history ,input ,weights ,raw_output ,silu_output , 256int (channels )); 257 }); 258 } 259check_launch (); 260} 261void native_gdn_l2_norm (float * input ,int64_t rows ,int64_t cols ,float epsilon ,void * stream ) { 262norm_geometry (rows ,cols ,epsilon ,stream ); 263valid ({input ,size_t (rows )* S * sizeof (float )}); 264 { 265auto exp_props = sycl::ext::oneapi::experimental::properties { 266 sycl::ext::oneapi::experimental::use_root_sync }; 267 268 strata::kprof::kp (strata::q_of (stream ),__FILE__ ,__func__ ,__LINE__ ) 269-> submit ([& ](sycl::handler & cgh ) { 270auto epsilon_S_ct1 = epsilon /S ; 271auto sqrtf_float_S_ct2 = 1.0f /sqrtf (float (S )); 272 273cgh .parallel_for < dpct_kernel_name < class l2_norm_bcf2af >> ( 274 sycl::nd_range < 3 > (sycl::range (1 ,1 ,unsigned (rows ))* 275 sycl::range (1 ,1 ,256 ), 276 sycl::range (1 ,1 ,256 )), 277exp_props , 278 [= ](sycl::nd_item < 3 > item_ct1 ) 279 [[sycl ::reqd_sub_group_size (32 )]] { 280l2_norm (input ,epsilon_S_ct1 ,sqrtf_float_S_ct2 ); 281 }); 282 }); 283 } 284check_launch (); 285} 286void native_gdn_beta_gate (float * beta ,int64_t heads ,void * stream ) { 287count_and_stream (heads ,stream ); 288valid ({beta ,size_t (heads )* sizeof (float )}); 289 { 290auto exp_props = sycl::ext::oneapi::experimental::properties { 291 sycl::ext::oneapi::experimental::use_root_sync }; 292 293 strata::kprof::kp (strata::q_of (stream ),__FILE__ ,__func__ ,__LINE__ ) 294-> template parallel_for < dpct_kernel_name < class beta_sigmoid_fcf68f >> ( 295 sycl::nd_range < 3 > ( 296 sycl::range (1 ,1 ,unsigned ((heads + 255 ) /256 ))* 297 sycl::range (1 ,1 ,256 ), 298 sycl::range (1 ,1 ,256 )), 299exp_props , [= ](sycl::nd_item < 3 > item_ct1 ) { 300beta_sigmoid (beta ,int (heads )); 301 }); 302 } 303check_launch (); 304} 305void native_gdn_gate (const float * alpha ,const float * dt ,const float * ssm_a , 306float * gate ,int64_t heads ,void * stream ) { 307count_and_stream (heads ,stream ); 308const size_t bytes = size_t (heads )* sizeof (float ); 309const Span output {gate ,bytes }; 310valid (output ); 311for (auto input : {Span {alpha ,bytes },Span {dt ,bytes },Span {ssm_a ,bytes }}) { 312valid (input ); 313disjoint (output ,input ); 314 } 315 { 316auto exp_props = sycl::ext::oneapi::experimental::properties { 317 sycl::ext::oneapi::experimental::use_root_sync }; 318 319 strata::kprof::kp (strata::q_of (stream ),__FILE__ ,__func__ ,__LINE__ ) 320-> template parallel_for < dpct_kernel_name < class gate_softplus_a95cee >> ( 321 sycl::nd_range < 3 > ( 322 sycl::range (1 ,1 ,unsigned ((heads + 255 ) /256 ))* 323 sycl::range (1 ,1 ,256 ), 324 sycl::range (1 ,1 ,256 )), 325exp_props , [= ](sycl::nd_item < 3 > item_ct1 ) { 326gate_softplus (alpha ,dt ,ssm_a ,gate ,int (heads )); 327 }); 328 } 329check_launch (); 330} 331void native_gdn_out_norm (const float * output ,const float * z ,const float * gamma , 332float * destination ,int64_t heads ,int64_t cols , 333float epsilon ,void * stream ) { 334norm_geometry (heads ,cols ,epsilon ,stream ); 335const size_t bytes = size_t (heads )* S * sizeof (float ); 336const Span writable {destination ,bytes }; 337valid (writable ); 338for (auto input : {Span {output ,bytes },Span {z ,bytes },Span {gamma ,S * sizeof (float )}}) { 339valid (input ); 340disjoint (writable ,input ); 341 } 342 { 343auto exp_props = sycl::ext::oneapi::experimental::properties { 344 sycl::ext::oneapi::experimental::use_root_sync }; 345 346 strata::kprof::kp (strata::q_of (stream ),__FILE__ ,__func__ ,__LINE__ ) 347-> template parallel_for < dpct_kernel_name < class out_norm_a49e35 >> ( 348 sycl::nd_range < 3 > (sycl::range (1 ,1 ,unsigned (heads ))* 349 sycl::range (1 ,1 ,256 ), 350 sycl::range (1 ,1 ,256 )), 351exp_props , 352 [= ](sycl::nd_item < 3 > item_ct1 ) 353 [[sycl ::reqd_sub_group_size (32 )]] { 354out_norm (output ,z ,gamma ,destination ,epsilon ); 355 }); 356 } 357check_launch (); 358} 359}// namespace strata::kernels