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}. 3// 4// MIT License 5// Copyright (c) 2023-2026 The ggml authors 6// 7// Permission is hereby granted, free of charge, to any person obtaining a copy 8// of this software and associated documentation files (the "Software"), to deal 9// in the Software without restriction, including without limitation the rights 10// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 11// copies of the Software, and to permit persons to whom the Software is 12// furnished to do so, subject to the following conditions: 13// 14// The above copyright notice and this permission notice shall be included in all 15// copies or substantial portions of the Software. 16// 17// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 18// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 19// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 20// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 21// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 22// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 23// SOFTWARE. 24 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_qsa.hpp" 31#include <atomic> 32#include <cmath> 33#include <cstddef> 34#include <cstdint> 35#include <limits> 36#include <stdexcept> 37#include <string> 38 39namespace strata::kernels { 40namespace { 41std::atomic < bool > enabled {false}; 42__dpct_inline__ float warp_sum (float value ) { 43#pragma unroll 44for (int offset = 16 ;offset ;offset >>=1 ) 45/* 46DPCT1108: '__shfl_xor_sync' was migrated with the experimental 47feature masked sub_group function which may not be supported by all 48compilers or runtimes. You may need to adjust the code. 49*/ 50value += dpct::experimental::permute_sub_group_by_xor ( 510xffffffffu , sycl::ext::oneapi::this_work_item::get_sub_group (), 52value ,offset ); 53return value ; 54} 55template < int BlockSize > 56__dpct_inline__ void norm (const float * input ,const float * __restrict__gamma , 57float * output ,int n_cols ,float epsilon ) { 58auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item < 3 > (); 59const int tid = item_ct1 .get_local_id (2 ); 60const std::size_t row_offset = std::size_t (item_ct1 .get_group (2 ))* n_cols ; 61input += row_offset ;output += row_offset ; 62float partial = 0.0f ; 63for (std::size_t col = tid ;col < std::size_t (n_cols );col += BlockSize ) { 64const float x = input [col ]; 65partial += x * x ; 66 } 67auto & sums = 68* sycl::ext::oneapi::group_local_memory_for_overwrite < float [32 ]> ( 69 sycl::ext::oneapi::this_work_item::get_work_group < 3 > ()); 70partial = warp_sum (partial ); 71const int lane = tid %32 ; 72if (lane == 0 )sums [tid /32 ]= partial ; 73// All reads of input for the reduction precede this barrier. Afterwards, 74// each thread reads/writes only its own elements, allowing exact in-place use. 75item_ct1 .barrier (sycl::access::fence_space::local_space ); 76partial = lane < BlockSize /32 ?sums [lane ] :0.0f ; 77partial = warp_sum (partial ); 78const float mean = partial /n_cols ; 79const float scale = sycl::rsqrt (mean + epsilon ); 80#pragma unroll 81for (std::size_t col = tid ;col < std::size_t (n_cols );col += BlockSize ) 82output [col ]= scale * input [col ]* gamma [col ]; 83} 84// As norm, with gamma[groups * n_cols]: row r is group r % groups and reads its own slice of gamma. 85template < int BlockSize > 86__dpct_inline__ void 87norm_grouped (const float * input ,const float * __restrict__gamma ,float * output , 88int n_cols ,int groups ,float epsilon ) { 89auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item < 3 > (); 90const int tid = item_ct1 .get_local_id (2 ); 91const std::size_t row_offset = std::size_t (item_ct1 .get_group (2 ))* n_cols ; 92input += row_offset ;output += row_offset ; 93gamma += std::size_t (item_ct1 .get_group (2 ) %unsigned (groups ))* n_cols ; 94float partial = 0.0f ; 95for (std::size_t col = tid ;col < std::size_t (n_cols );col += BlockSize ) { 96const float x = input [col ]; 97partial += x * x ; 98 } 99auto & sums = 100* sycl::ext::oneapi::group_local_memory_for_overwrite < float [32 ]> ( 101 sycl::ext::oneapi::this_work_item::get_work_group < 3 > ()); 102partial = warp_sum (partial ); 103const int lane = tid %32 ; 104if (lane == 0 )sums [tid /32 ]= partial ; 105item_ct1 .barrier (sycl::access::fence_space::local_space ); 106partial = lane < BlockSize /32 ?sums [lane ] :0.0f ; 107partial = warp_sum (partial ); 108const float mean = partial /n_cols ; 109const float scale = sycl::rsqrt (mean + epsilon ); 110#pragma unroll 111for (std::size_t col = tid ;col < std::size_t (n_cols );col += BlockSize ) 112output [col ]= scale * input [col ]* gamma [col ]; 113} 114__dpct_inline__ void gate (const float * attn ,const float * __restrict__q_full , 115float * output ,int n_head ,int head_dim ) { 116auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item < 3 > (); 117const std::size_t i = 118 std::size_t (item_ct1 .get_group (2 ))* item_ct1 .get_local_range (2 )+ 119item_ct1 .get_local_id (2 ); 120if (i >= std::size_t (n_head )* head_dim )return ; 121const std::size_t head = i /head_dim ,channel = i %head_dim ; 122const float raw = q_full [head * 2 * head_dim + head_dim + channel ]; 123const float sigmoid = 1.0f / (1.0f + sycl::native::exp (- raw )); 124output [i ]= attn [i ]* sigmoid ; 125} 126std::size_t elements (int cols ,int rows ) { 127if (cols <=0 || rows <=0 || std::uint64_t (cols )* rows > std::uint64_t (std::numeric_limits < int > ::max ())) 128throw std::invalid_argument ("native QSA requires positive bounded dimensions" ); 129return std::size_t (cols )* rows ; 130} 131bool valid (const void * ptr , std::size_t bytes ) { 132const auto address = reinterpret_cast < std::uintptr_t > (ptr ); 133return ptr && address %4 == 0 && bytes <=UINTPTR_MAX - address ; 134} 135bool overlap (const void * a , std::size_t an ,const void * b , std::size_t bn ) { 136const auto ap = reinterpret_cast < std::uintptr_t > (a ),bp = reinterpret_cast < std::uintptr_t > (b ); 137return ap < bp + bn && bp < ap + an ; 138} 139void buffers (const float * input , std::size_t in_bytes ,const float * weight , std::size_t weight_bytes , 140float * output ,void * stream ) { 141if (!stream || !valid (input ,in_bytes )|| !valid (weight ,weight_bytes )|| !valid (output ,in_bytes )|| 142overlap (input ,in_bytes ,weight ,weight_bytes )|| overlap (output ,in_bytes ,weight ,weight_bytes )|| 143 (input != output && overlap (input ,in_bytes ,output ,in_bytes ))) 144throw std::invalid_argument ("native QSA requires a stream, aligned spans, and disjoint buffers or exact input/output alias" ); 145} 146void check_launch () { 147/* 148DPCT1010: SYCL uses exceptions to report errors and does not use the 149error codes. The cudaGetLastError function call was replaced with 0. You 150need to rewrite this code. 151*/ 152const auto result = 0 ; 153/* 154DPCT1000: Error handling if-stmt was detected but could not be 155rewritten. 156*/ 157if (result != 0 ) 158/* 159DPCT1009: SYCL reports errors using exceptions and does not use 160error codes. Please replace the "get_error_string_dummy(...)" with a 161real error-handling function. 162*/ 163/* 164DPCT1001: The statement could not be removed. 165*/ 166throw std::runtime_error (std::string ("native QSA launch: " )+ 167 dpct::get_error_string_dummy (result )); 168} 169}// namespace 170 171void native_qsa_set_enabled (bool value ) {enabled .store (value , std::memory_order_relaxed ); } 172bool native_qsa_enabled () {return enabled .load (std::memory_order_relaxed ); } 173 174void native_qsa_rms_norm_weighted (const float * input ,const float * gamma ,float * output , 175int n_cols ,int n_rows ,float epsilon ,void * stream ) { 176const auto count = elements (n_cols ,n_rows ); 177if (!std::isfinite (epsilon )|| epsilon < 0.0f ) 178throw std::invalid_argument ("native QSA requires finite nonnegative epsilon" ); 179buffers (input ,count * 4 ,gamma , std::size_t (n_cols )* 4 ,output ,stream ); 180if (n_cols < 1024 ) 181 { 182auto exp_props = sycl::ext::oneapi::experimental::properties { 183 sycl::ext::oneapi::experimental::use_root_sync }; 184 185 strata::kprof::kp (strata::q_of (stream ),__FILE__ ,__func__ ,__LINE__ ) 186-> template parallel_for < 187dpct_kernel_name < class norm_5d08bf ,dpct_kernel_scalar < 256 >>> ( 188 sycl::nd_range < 3 > (sycl::range (1 ,1 ,unsigned (n_rows ))* 189 sycl::range (1 ,1 ,256 ), 190 sycl::range (1 ,1 ,256 )), 191exp_props , 192 [= ](sycl::nd_item < 3 > item_ct1 ) 193 [[sycl ::reqd_sub_group_size (32 )]] { 194norm < 256 > (input ,gamma ,output ,n_cols ,epsilon ); 195 }); 196 }else 197/* 198DPCT1049: The work-group size passed to the SYCL kernel may exceed 199the limit. To get the device limit, query 200info::device::max_work_group_size. Adjust the work-group size if needed. 201*/ 202 { 203auto exp_props = sycl::ext::oneapi::experimental::properties { 204 sycl::ext::oneapi::experimental::use_root_sync }; 205 206 strata::kprof::kp (strata::q_of (stream ),__FILE__ ,__func__ ,__LINE__ ) 207-> template parallel_for < 208dpct_kernel_name < class norm_127936 ,dpct_kernel_scalar < 1024 >>> ( 209 sycl::nd_range < 3 > (sycl::range (1 ,1 ,unsigned (n_rows ))* 210 sycl::range (1 ,1 ,1024 ), 211 sycl::range (1 ,1 ,1024 )), 212exp_props , 213 [= ](sycl::nd_item < 3 > item_ct1 ) 214 [[sycl ::reqd_sub_group_size (32 )]] { 215norm < 1024 > (input ,gamma ,output ,n_cols ,epsilon ); 216 }); 217 } 218check_launch (); 219} 220void native_qsa_rms_norm_grouped (const float * input ,const float * gamma ,float * output , 221int n_cols ,int groups ,int n_rows ,float epsilon ,void * stream ) { 222if (groups < 1 )throw std::invalid_argument ("native QSA requires positive bounded dimensions" ); 223const auto count = elements (n_cols ,n_rows ); 224if (!std::isfinite (epsilon )|| epsilon < 0.0f ) 225throw std::invalid_argument ("native QSA requires finite nonnegative epsilon" ); 226buffers (input ,count * 4 ,gamma , std::size_t (n_cols )* groups * 4 ,output ,stream ); 227if (n_cols < 1024 ) 228 { 229auto exp_props = sycl::ext::oneapi::experimental::properties { 230 sycl::ext::oneapi::experimental::use_root_sync }; 231 232 strata::kprof::kp (strata::q_of (stream ),__FILE__ ,__func__ ,__LINE__ ) 233-> template parallel_for < dpct_kernel_name < class norm_grouped_b5907a , 234dpct_kernel_scalar < 256 >>> ( 235 sycl::nd_range < 3 > (sycl::range (1 ,1 ,unsigned (n_rows ))* 236 sycl::range (1 ,1 ,256 ), 237 sycl::range (1 ,1 ,256 )), 238exp_props , 239 [= ](sycl::nd_item < 3 > item_ct1 ) 240 [[sycl ::reqd_sub_group_size (32 )]] { 241norm_grouped < 256 > (input ,gamma ,output ,n_cols ,groups , 242epsilon ); 243 }); 244 }else 245/* 246DPCT1049: The work-group size passed to the SYCL kernel may exceed 247the limit. To get the device limit, query 248info::device::max_work_group_size. Adjust the work-group size if needed. 249*/ 250 { 251auto exp_props = sycl::ext::oneapi::experimental::properties { 252 sycl::ext::oneapi::experimental::use_root_sync }; 253 254 strata::kprof::kp (strata::q_of (stream ),__FILE__ ,__func__ ,__LINE__ ) 255-> template parallel_for < dpct_kernel_name < class norm_grouped_927e80 , 256dpct_kernel_scalar < 1024 >>> ( 257 sycl::nd_range < 3 > (sycl::range (1 ,1 ,unsigned (n_rows ))* 258 sycl::range (1 ,1 ,1024 ), 259 sycl::range (1 ,1 ,1024 )), 260exp_props , 261 [= ](sycl::nd_item < 3 > item_ct1 ) 262 [[sycl ::reqd_sub_group_size (32 )]] { 263norm_grouped < 1024 > (input ,gamma ,output ,n_cols ,groups , 264epsilon ); 265 }); 266 } 267check_launch (); 268} 269void native_qsa_gate_apply (const float * attn ,const float * q_full ,float * output , 270int n_head ,int head_dim ,void * stream ) { 271const auto count = elements (head_dim ,n_head ); 272buffers (attn ,count * 4 ,q_full ,count * 8 ,output ,stream ); 273 { 274auto exp_props = sycl::ext::oneapi::experimental::properties { 275 sycl::ext::oneapi::experimental::use_root_sync }; 276 277 strata::kprof::kp (strata::q_of (stream ),__FILE__ ,__func__ ,__LINE__ ) 278-> template parallel_for < dpct_kernel_name < class gate_148967 >> ( 279 sycl::nd_range < 3 > ( 280 sycl::range (1 ,1 ,unsigned ((count + 255 ) /256 ))* 281 sycl::range (1 ,1 ,256 ), 282 sycl::range (1 ,1 ,256 )), 283exp_props , [= ](sycl::nd_item < 3 > item_ct1 ) { 284gate (attn ,q_full ,output ,n_head ,head_dim ); 285 }); 286 } 287check_launch (); 288} 289}// namespace strata::kernels