okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
86bed1c92
main
1// Specialized from llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d, 2// ggml/src/ggml-cuda/{fattn-vec.cuh,fattn-common.cuh,common.cuh}. 3// MIT License 4// Copyright (c) 2023-2026 The ggml authors 5// Permission is hereby granted, free of charge, to any person obtaining a copy 6// of this software and associated documentation files (the "Software"), to deal 7// in the Software without restriction, including without limitation the rights 8// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9// copies of the Software, and to permit persons to whom the Software is 10// furnished to do so, subject to the following conditions: 11// The above copyright notice and this permission notice shall be included in all 12// copies or substantial portions of the Software. 13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 19// SOFTWARE. 20 21#define DPCT_PROFILING_ENABLED 22#include <sycl/sycl.hpp> 23#include "strata/kprof.hpp" 24#include <dpct/dpct.hpp> 25#include "strata/sycl_queue.hpp" 26#include "strata/kernels/native_flash_attn.hpp" 27#include <cfloat> 28#include <cstddef> 29#include <cstdint> 30#include <limits> 31#include <stdexcept> 32#include <string> 33#include <cmath> 34 35namespace strata::kernels { 36namespace { 37template < int Width > __dpct_inline__ float warp_sum (float x ) { 38#pragma unroll 39for (int offset = Width /2 ;offset ;offset >>=1 ) 40/* 41DPCT1108: '__shfl_xor_sync' was migrated with the experimental 42feature masked sub_group function which may not be supported by all 43compilers or runtimes. You may need to adjust the code. 44*/ 45x += dpct::experimental::permute_sub_group_by_xor ( 460xffffffffu , sycl::ext::oneapi::this_work_item::get_sub_group (),x , 47offset ,Width ); 48return x ; 49} 50__dpct_inline__ float warp_max (float x ) { 51#pragma unroll 52for (int offset = 16 ;offset ;offset >>=1 ) 53/* 54DPCT1108: '__shfl_xor_sync' was migrated with the experimental 55feature masked sub_group function which may not be supported by all 56compilers or runtimes. You may need to adjust the code. 57*/ 58x = sycl::fmax (x , 59 dpct::experimental::permute_sub_group_by_xor ( 600xffffffffu , 61 sycl::ext::oneapi::this_work_item::get_sub_group (), 62x ,offset )); 63return x ; 64} 65 66// D=256,ncols=1,F16/F16; 128 threads, nthreads_KQ=nthreads_V=8, 67// four values (float2) per load, four V columns per iteration. Padded length256 68// gives ntiles_KV=ceil(256/D)=1, so the pinned launcher selects grid.y=1. 69/* 70DPCT1110: The total declared local variable size in device function attend 71exceeds 128 bytes and may cause high register pressure. Consult with your 72hardware vendor to find the total register size available and adjust the code, 73or use smaller sub-group size to avoid high register pressure. 74*/ 75__dpct_inline__ void 76attend (const float * __restrict__q ,const sycl::half * __restrict__k , 77const sycl::half * __restrict__v ,const int32_t * __restrict__step , 78int max_context ,int padded_length ,float scale ,float * __restrict__out , 79int32_t * __restrict__status ,const sycl::half * __restrict__mask ) { 80auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item < 3 > (); 81const int lane = item_ct1 .get_local_id (2 ),warp = item_ct1 .get_local_id (1 ), 82tid = warp * 32 + lane ; 83const int head = item_ct1 .get_group (2 ),kv = head /12 ; 84const int width = step [kStepWidth ],nkv = step [kStepNKv ]; 85const bool valid = width >=1 && width <=max_context && nkv == width && 86step [kStepPos ]== width - 1 && step [kStepNBid ]== width /4 ; 87if (head == 0 && tid == 0 ) 88* status = valid ?kNativeFlashAttnSuccess :kNativeFlashAttnUnsupportedStep ; 89if (!valid ) { 90out [head * 256 + tid ]= sycl::bit_cast < float > (0x7fc00000 ); 91out [head * 256 + tid + 128 ]= sycl::bit_cast < float > (0x7fc00000 ); 92return ; 93 } 94 sycl::float2 qreg [16 ]; 95 sycl::float2 vkq [16 ]= {}; 96auto & tile = * sycl::ext::oneapi::group_local_memory_for_overwrite < 97float [4 * 4 * 256 ]> ( 98 sycl::ext::oneapi::this_work_item::get_work_group < 3 > ()); 99auto & max_shared = 100* sycl::ext::oneapi::group_local_memory_for_overwrite < float [32 ]> ( 101 sycl::ext::oneapi::this_work_item::get_work_group < 3 > ()); 102auto & sum_shared = 103* sycl::ext::oneapi::group_local_memory_for_overwrite < float [32 ]> ( 104 sycl::ext::oneapi::this_work_item::get_work_group < 3 > ()); 105float maximum = - FLT_MAX /2.0f ,sum = 0.0f ; 106#pragma unroll 107for (int i0 = 0 ;i0 < 128 ;i0 += 32 ) { 108const int i = i0 + (lane %8 )* 4 ; 109#pragma unroll 110for (int j = 0 ;j < 4 ;++ j ) { 111const int d = 2 * (i + j ); 112qreg [i0 /8 + j ]= sycl::float2 (q [head * 256 + d ]* scale , 113q [head * 256 + d + 1 ]* scale ); 114 } 115 } 116for (int base = 0 ;base < padded_length ;base += 128 ) { 117float score = 0.0f ,next_max = maximum ; 118#pragma unroll 119for (int row = 0 ;row < 8 ;++ row ) { 120const int cell = base + warp * 32 + (lane & ~7 )+ row ; 121float dot = 0.0f ; 122#pragma unroll 123for (int i0 = 0 ;i0 < 128 ;i0 += 32 ) { 124const int i = i0 + (lane %8 )* 4 ; 125#pragma unroll 126for (int j = 0 ;j < 4 ;++ j ) { 127const int d = 2 * (i + j ); 128const float a = 129cell < width 130 ? sycl::vec < sycl::half ,1 > ( 131k [(cell * 2 + kv )* 256 + d ]) 132 .convert < float , 133 sycl::rounding_mode::automatic > ()[0 ] 134 :0.0f ; 135const float b = 136cell < width 137 ? sycl::vec < sycl::half ,1 > ( 138k [(cell * 2 + kv )* 256 + d + 1 ]) 139 .convert < float , 140 sycl::rounding_mode::automatic > ()[0 ] 141 :0.0f ; 142dot += a * qreg [i0 /8 + j ].x (); 143dot += b * qreg [i0 /8 + j ].y (); 144 } 145 } 146dot = warp_sum < 8 > (dot ); 147dot += 148cell < width 149 ? (mask ? sycl::vec < sycl::half ,1 > (mask [cell ]) 150 .convert < float , 151 sycl::rounding_mode::automatic > ()[0 ] 152 :0.0f ) 153 : sycl::bit_cast < float ,int > (0xff800000u ); 154next_max = sycl::fmax (next_max ,dot + (3.0f * 0.6931f )); 155if (lane %8 == row )score = dot ; 156 } 157#pragma unroll 158for (int offset = 8 ;offset < 32 ;offset <<=1 ) 159/* 160DPCT1108: '__shfl_xor_sync' was migrated with the experimental 161feature masked sub_group function which may not be supported by all 162compilers or runtimes. You may need to adjust the code. 163*/ 164next_max = sycl::fmax ( 165next_max , 166 dpct::experimental::permute_sub_group_by_xor ( 1670xffffffffu , 168 sycl::ext::oneapi::this_work_item::get_sub_group (), 169next_max ,offset )); 170const float rescale = sycl::native::exp (maximum - next_max ); 171maximum = next_max ; 172score = sycl::native::exp (score - maximum ); 173sum = sum * rescale + score ; 174tile [tid ]= score ; 175 sycl::group_barrier (sycl::ext::oneapi::this_work_item::get_sub_group ()); 176#pragma unroll 177for (int k0 = 0 ;k0 < 32 ;k0 += 4 ) { 178const int local = warp * 32 + k0 + lane /8 ,cell = base + local ; 179const float weight = tile [local ]; 180#pragma unroll 181for (int i0 = 0 ;i0 < 128 ;i0 += 32 ) { 182const int i = i0 + (lane %8 )* 4 ; 183#pragma unroll 184for (int j = 0 ;j < 4 ;++ j ) { 185const int d = 2 * (i + j ); 186const float a = 187cell < width 188 ? sycl::vec < sycl::half ,1 > ( 189v [(cell * 2 + kv )* 256 + d ]) 190 .convert < float , 191 sycl::rounding_mode::automatic > ()[0 ] 192 :0.0f ; 193const float b = 194cell < width 195 ? sycl::vec < sycl::half ,1 > ( 196v [(cell * 2 + kv )* 256 + d + 1 ]) 197 .convert < float , 198 sycl::rounding_mode::automatic > ()[0 ] 199 :0.0f ; 200// The pinned sm120a binary contracts the old-accumulator 201// rescale with the FIRST addition: fma(rescale,old,round(V*w)). 202// Later columns use fma(V,w,acc). Explicit intrinsics retain 203// that order despite this adapter's masked-load branches. 204if (k0 == 0 ) { 205/* 206DPCT1013: The rounding mode could not be specified 207and the generated code may have different accuracy than 208the original code. Verify the correctness. SYCL math 209built-in function rounding mode is aligned with OpenCL 210C 1.2 standard. 211*/ 212vkq [i0 /8 + j ].x ()= 213 sycl::fma (rescale ,vkq [i0 /8 + j ].x (),a * weight ); 214/* 215DPCT1013: The rounding mode could not be specified 216and the generated code may have different accuracy than 217the original code. Verify the correctness. SYCL math 218built-in function rounding mode is aligned with OpenCL 219C 1.2 standard. 220*/ 221vkq [i0 /8 + j ].y ()= 222 sycl::fma (rescale ,vkq [i0 /8 + j ].y (),b * weight ); 223 }else { 224/* 225DPCT1013: The rounding mode could not be specified 226and the generated code may have different accuracy than 227the original code. Verify the correctness. SYCL math 228built-in function rounding mode is aligned with OpenCL 229C 1.2 standard. 230*/ 231vkq [i0 /8 + j ].x ()= 232 sycl::fma (a ,weight ,vkq [i0 /8 + j ].x ()); 233/* 234DPCT1013: The rounding mode could not be specified 235and the generated code may have different accuracy than 236the original code. Verify the correctness. SYCL math 237built-in function rounding mode is aligned with OpenCL 238C 1.2 standard. 239*/ 240vkq [i0 /8 + j ].y ()= 241 sycl::fma (b ,weight ,vkq [i0 /8 + j ].y ()); 242 } 243 } 244 } 245 } 246 } 247if (warp == 0 ) {max_shared [lane ]= - FLT_MAX /2.0f ;sum_shared [lane ]= 0.0f ; } 248/* 249DPCT1065: Consider replacing sycl::nd_item::barrier() with 250sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better 251performance if there is no access to global memory. 252*/ 253item_ct1 .barrier (); 254if (lane == 0 )max_shared [warp ]= maximum ; 255/* 256DPCT1065: Consider replacing sycl::nd_item::barrier() with 257sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better 258performance if there is no access to global memory. 259*/ 260item_ct1 .barrier (); 261const float global_max = warp_max (max_shared [lane ]); 262const float rescale = sycl::native::exp (maximum - global_max ); 263#pragma unroll 264for (int i = 0 ;i < 16 ;++ i ) { 265/* 266DPCT1013: The rounding mode could not be specified and the 267generated code may have different accuracy than the original code. 268Verify the correctness. SYCL math built-in function rounding mode is 269aligned with OpenCL C 1.2 standard. 270*/ 271vkq [i ].x ()= vkq [i ].x ()* rescale ; 272/* 273DPCT1013: The rounding mode could not be specified and the 274generated code may have different accuracy than the original code. 275Verify the correctness. SYCL math built-in function rounding mode is 276aligned with OpenCL C 1.2 standard. 277*/ 278vkq [i ].y ()= vkq [i ].y ()* rescale ; 279 } 280#pragma unroll 281for (int i0 = 0 ;i0 < 128 ;i0 += 32 ) { 282const int start = warp * 4 * 256 + (lane /8 )* 256 + 2 * (i0 + (lane %8 )* 4 ); 283#pragma unroll 284for (int j = 0 ;j < 4 ;++ j ) { 285tile [start + 2 * j ]= vkq [i0 /8 + j ].x (); 286tile [start + 2 * j + 1 ]= vkq [i0 /8 + j ].y (); 287 } 288 } 289sum *=rescale ; 290sum = warp_sum < 32 > (sum ); 291if (lane == 0 )sum_shared [warp ]= sum ; 292/* 293DPCT1065: Consider replacing sycl::nd_item::barrier() with 294sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better 295performance if there is no access to global memory. 296*/ 297item_ct1 .barrier (); 298sum = warp_sum < 32 > (sum_shared [lane ]); 299#pragma unroll 300for (int i0 = 0 ;i0 < 256 ;i0 += 128 ) { 301float result = 0.0f ; 302#pragma unroll 303for (int w = 0 ;w < 4 ;++ w ) { 304#pragma unroll 305for (int group = 0 ;group < 4 ;++ group ) 306result += tile [w * 4 * 256 + group * 256 + i0 + tid ]; 307 } 308out [head * 256 + i0 + tid ]= result /sum ; 309 } 310} 311struct Span {const void * p ; std::size_t n ,alignment ; }; 312void validate_spans (const Span * spans ,int count ) { 313for (int i = 0 ;i < count ;++ i ) { 314const auto a = reinterpret_cast < std::uintptr_t > (spans [i ].p ); 315if (!a || a %spans [i ].alignment || spans [i ].n > UINTPTR_MAX - a ) 316throw std::invalid_argument ("native FlashAttention requires nonnull aligned bounded spans" ); 317for (int j = 0 ;j < i ;++ j ) { 318const auto b = reinterpret_cast < std::uintptr_t > (spans [j ].p ); 319if (a < b + spans [j ].n && b < a + spans [i ].n ) 320throw std::invalid_argument ("native FlashAttention requires disjoint buffers" ); 321 } 322 } 323} 324}// namespace 325 326void native_flash_attn_short_step (const float * q ,const uint16_t * k ,const uint16_t * v , 327const int32_t * step ,int64_t capacity ,int max_context , 328const QsaShapes & shapes ,float * output ,int32_t * status , 329const uint16_t * mask ,void * stream ) { 330if (!stream || shapes .n_head != 24 || shapes .n_head_kv != 2 || shapes .head_dim != 256 || 331shapes .idx_block != 4 || shapes .idx_top_k < 256 || capacity < 256 || 332uint64_t (capacity )> std::numeric_limits < std::size_t > ::max () /1024 || 333max_context < 1 || max_context > 256 ) 334throw std::invalid_argument ("native FlashAttention supports only Q24x256/KV2x256, capacity>=256 and context1..256 on an explicit stream" ); 335const std::size_t kv_bytes = std::size_t (capacity )* 1024 ; 336const Span spans []= {{q ,24 * 256 * 4 ,4 }, {k ,kv_bytes ,2 }, {v ,kv_bytes ,2 }, 337 {step ,kStepCount * 4 ,4 }, {output ,24 * 256 * 4 ,4 }, 338 {status ,4 ,4 }, {mask ,256 * 2 ,2 }}; 339validate_spans (spans ,mask ?7 :6 ); 340 { 341auto exp_props = sycl::ext::oneapi::experimental::properties { 342 sycl::ext::oneapi::experimental::use_root_sync }; 343 dpct::has_capability_or_fail ( 344 ((sycl::queue * )(strata::q_of (stream ))) 345-> get_device (), 346 {sycl::aspect::fp16 }); 347 348 strata::kprof::kp (strata::q_of (stream ),__FILE__ ,__func__ ,__LINE__ ) 349-> template parallel_for < dpct_kernel_name < class attend_9d5505 >> ( 350 sycl::nd_range < 3 > (sycl::range (1 ,1 ,24 )* sycl::range (1 ,4 ,32 ), 351 sycl::range (1 ,4 ,32 )), 352exp_props , 353 [= ](sycl::nd_item < 3 > item_ct1 ) 354 [[sycl ::reqd_sub_group_size (32 )]] { 355attend (q ,reinterpret_cast < const sycl::half *> (k ), 356reinterpret_cast < const sycl::half *> (v ),step , 357max_context ,256 ,0.0625f ,output ,status , 358reinterpret_cast < const sycl::half *> (mask )); 359 }); 360 } 361/* 362DPCT1010: SYCL uses exceptions to report errors and does not use the 363error codes. The cudaGetLastError function call was replaced with 0. You 364need to rewrite this code. 365*/ 366const auto result = 0 ; 367/* 368DPCT1000: Error handling if-stmt was detected but could not be 369rewritten. 370*/ 371if (result != 0 ) 372/* 373DPCT1009: SYCL reports errors using exceptions and does not use 374error codes. Please replace the "get_error_string_dummy(...)" with a 375real error-handling function. 376*/ 377/* 378DPCT1001: The statement could not be removed. 379*/ 380throw std::runtime_error (std::string ("native FlashAttention launch: " )+ 381 dpct::get_error_string_dummy (result )); 382} 383}// namespace strata::kernels