okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
86bed1c92
main
1// Adapted from topk-moe.cu/common.cuh in llama.cpp 2// 3cf03257f219afbe7334045ff7c6a06ac68c627d; finite F32, 512-expert/10-output path. 3// MIT License 4// Copyright (c) 2023-2026 The ggml authors 5// 6// Permission is hereby granted, free of charge, to any person obtaining a copy 7// of this software and associated documentation files (the "Software"), to deal 8// in the Software without restriction, including without limitation the rights 9// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10// copies of the Software, and to permit persons to whom the Software is 11// furnished to do so, subject to the following conditions: 12// 13// The above copyright notice and this permission notice shall be included in all 14// copies or substantial portions of the Software. 15// 16// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22// SOFTWARE. 23#define DPCT_PROFILING_ENABLED 24#include <sycl/sycl.hpp> 25#include "strata/kprof.hpp" 26#include <dpct/dpct.hpp> 27#include "strata/sycl_queue.hpp" 28#include "strata/kernels/native_router.hpp" 29#include <atomic> 30#include <cfloat> 31#include <cstddef> 32#include <cstdint> 33#include <stdexcept> 34 35namespace strata::kernels { 36namespace { 37std::atomic < bool > enabled {false}; 38__dpct_inline__ float warp_sum (float value ) { 39#pragma unroll 40/* 41DPCT1108: '__shfl_xor_sync' was migrated with the experimental feature 42masked sub_group function which may not be supported by all compilers or 43runtimes. You may need to adjust the code. 44*/ 45for (int mask = 16 ;mask ;mask >>=1 )value += 46 dpct::experimental::permute_sub_group_by_xor ( 470xffffffffu , sycl::ext::oneapi::this_work_item::get_sub_group (), 48value ,mask ); 49return value ; 50} 51__dpct_inline__ float warp_max (float value ) { 52#pragma unroll 53/* 54DPCT1108: '__shfl_xor_sync' was migrated with the experimental feature 55masked sub_group function which may not be supported by all compilers or 56runtimes. You may need to adjust the code. 57*/ 58for (int mask = 16 ;mask ;mask >>=1 )value = sycl::fmax ( 59value , 60 dpct::experimental::permute_sub_group_by_xor ( 610xffffffffu , sycl::ext::oneapi::this_work_item::get_sub_group (), 62value ,mask )); 63return value ; 64} 65/* 66DPCT1110: The total declared local variable size in device function route 67exceeds 128 bytes and may cause high register pressure. Consult with your 68hardware vendor to find the total register size available and adjust the code, 69or use smaller sub-group size to avoid high register pressure. 70*/ 71template < int NE > // SYCL port: 512 (canonical) or 256 (the Coder) experts, 32 lanes x NE/32 values 72__dpct_inline__ void route (const float * __restrict__logits , 73int32_t * __restrict__ids , 74float * __restrict__weights ) { 75// Preserve the pinned 32x8 block geometry; only row zero is active here. 76// blockIdx.x = the token (a multi-token launch; 0 for the single one) 77auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item < 3 > (); 78logits += (size_t )item_ct1 .get_group (2 )* NE ; 79ids += (size_t )item_ct1 .get_group (2 )* 10 ; 80weights += (size_t )item_ct1 .get_group (2 )* 10 ; 81if (item_ct1 .get_local_id (1 )!= 0 )return ; 82const int lane = item_ct1 .get_local_id (2 ); 83float values [NE /32 ]; 84#pragma unroll 85for (int i = 0 ;i < NE /32 ;++ i )values [i ]= logits [lane + i * 32 ]; 86// Only subgroup row zero reaches this point (the other rows returned above): a work-group barrier here is 87// divergent and hangs on Alchemist (A770); the subgroup barrier is the one the surviving row can meet. 88 sycl::group_barrier (item_ct1 .get_sub_group ()); 89float maximum = - INFINITY ; 90#pragma unroll 91for (int i = 0 ;i < NE /32 ;++ i )maximum = sycl::max (maximum ,values [i ]); 92maximum = warp_max (maximum ); 93float sum = 0.0f ; 94#pragma unroll 95for (int i = 0 ;i < NE /32 ;++ i ) { 96values [i ]= sycl::native::exp (values [i ]- maximum ); 97sum += values [i ]; 98 } 99const float reciprocal = 1.0f /warp_sum (sum ); 100#pragma unroll 101for (int i = 0 ;i < NE /32 ;++ i ) { 102values [i ] *=reciprocal ; 103if (sycl::isnan (values [i ]))values [i ]= - FLT_MAX ; 104 } 105float selected = 0.0f ,selected_sum = 0.0f ; 106for (int rank = 0 ;rank < 10 ;++ rank ) { 107float best = values [0 ]; 108int expert = lane ; 109#pragma unroll 110for (int i = 1 ;i < NE /32 ;++ i ) { 111if (values [i ]> best ) {best = values [i ];expert = lane + i * 32 ; } 112 } 113#pragma unroll 114for (int mask = 16 ;mask ;mask >>=1 ) { 115/* 116DPCT1108: '__shfl_xor_sync' was migrated with the experimental 117feature masked sub_group function which may not be supported by all 118compilers or runtimes. You may need to adjust the code. 119*/ 120const float other = dpct::experimental::permute_sub_group_by_xor ( 1210xffffffffu , sycl::ext::oneapi::this_work_item::get_sub_group (), 122best ,mask ); 123/* 124DPCT1108: '__shfl_xor_sync' was migrated with the experimental 125feature masked sub_group function which may not be supported by all 126compilers or runtimes. You may need to adjust the code. 127*/ 128const int other_id = dpct::experimental::permute_sub_group_by_xor ( 1290xffffffffu , sycl::ext::oneapi::this_work_item::get_sub_group (), 130expert ,mask ); 131if (other > best || (other == best && other_id < expert )) {best = other ;expert = other_id ; } 132 } 133if ((expert & 31 )== lane ) { 134values [expert /32 ]= - INFINITY ; 135ids [rank ]= expert ; 136// Deliberately accumulate by WINNING EXPERT lane, not output rank. 137// Multiple selected experts in one lane add in selection order. 138selected_sum += best ; 139 } 140if (rank == lane )selected = best ; 141 } 142selected_sum = sycl::max (warp_sum (selected_sum ),6.103515625e-5f ); 143const float inverse_selected_sum = 1.0f /selected_sum ; 144if (lane < 10 )weights [lane ]= selected * inverse_selected_sum ; 145} 146/* 147DPCT1110: The total declared local variable size in device function 148route_multi exceeds 128 bytes and may cause high register pressure. Consult with 149your hardware vendor to find the total register size available and adjust the 150code, or use smaller sub-group size to avoid high register pressure. 151*/ 152__dpct_inline__ void route_multi (const float * __restrict__logits , 153int32_t * __restrict__ids , 154float * __restrict__weights ,int n_tok ) { 155auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item < 3 > (); 156const int tk = 157 (int )item_ct1 .get_group (2 )* 8 + (int )item_ct1 .get_local_id (1 ); 158if (tk >=n_tok )return ; 159logits += (size_t )tk * 512 ;ids += (size_t )tk * 10 ;weights += (size_t )tk * 10 ; 160const int lane = item_ct1 .get_local_id (2 ); 161float values [16 ]; 162#pragma unroll 163for (int i = 0 ;i < 16 ;++ i )values [i ]= logits [lane + i * 32 ]; 164 sycl::group_barrier (sycl::ext::oneapi::this_work_item::get_sub_group ()); 165float maximum = - INFINITY ; 166#pragma unroll 167for (int i = 0 ;i < 16 ;++ i )maximum = sycl::max (maximum ,values [i ]); 168maximum = warp_max (maximum ); 169float sum = 0.0f ; 170#pragma unroll 171for (int i = 0 ;i < 16 ;++ i ) { 172values [i ]= sycl::native::exp (values [i ]- maximum ); 173sum += values [i ]; 174 } 175const float reciprocal = 1.0f /warp_sum (sum ); 176#pragma unroll 177for (int i = 0 ;i < 16 ;++ i ) { 178values [i ] *=reciprocal ; 179if (sycl::isnan (values [i ]))values [i ]= - FLT_MAX ; 180 } 181float selected = 0.0f ,selected_sum = 0.0f ; 182for (int rank = 0 ;rank < 10 ;++ rank ) { 183float best = values [0 ]; 184int expert = lane ; 185#pragma unroll 186for (int i = 1 ;i < 16 ;++ i ) { 187if (values [i ]> best ) {best = values [i ];expert = lane + i * 32 ; } 188 } 189#pragma unroll 190for (int mask = 16 ;mask ;mask >>=1 ) { 191/* 192DPCT1108: '__shfl_xor_sync' was migrated with the experimental 193feature masked sub_group function which may not be supported by all 194compilers or runtimes. You may need to adjust the code. 195*/ 196const float other = dpct::experimental::permute_sub_group_by_xor ( 1970xffffffffu , sycl::ext::oneapi::this_work_item::get_sub_group (), 198best ,mask ); 199/* 200DPCT1108: '__shfl_xor_sync' was migrated with the experimental 201feature masked sub_group function which may not be supported by all 202compilers or runtimes. You may need to adjust the code. 203*/ 204const int other_id = dpct::experimental::permute_sub_group_by_xor ( 2050xffffffffu , sycl::ext::oneapi::this_work_item::get_sub_group (), 206expert ,mask ); 207if (other > best || (other == best && other_id < expert )) {best = other ;expert = other_id ; } 208 } 209if ((expert & 31 )== lane ) { 210values [expert /32 ]= - INFINITY ; 211ids [rank ]= expert ; 212selected_sum += best ; 213 } 214if (rank == lane )selected = best ; 215 } 216selected_sum = sycl::max (warp_sum (selected_sum ),6.103515625e-5f ); 217const float inverse_selected_sum = 1.0f /selected_sum ; 218if (lane < 10 )weights [lane ]= selected * inverse_selected_sum ; 219} 220bool valid (const void * p ,size_t bytes ) { 221const auto address = reinterpret_cast < uintptr_t > (p ); 222return p && address %4 == 0 && bytes <=UINTPTR_MAX - address ; 223} 224bool overlap (const void * a ,size_t an ,const void * b ,size_t bn ) { 225const auto ap = reinterpret_cast < uintptr_t > (a ),bp = reinterpret_cast < uintptr_t > (b ); 226return ap < bp + bn && bp < ap + an ; 227} 228} 229void native_router_set_enabled (bool value ) {enabled .store (value , std::memory_order_relaxed ); } 230bool native_router_enabled () {return enabled .load (std::memory_order_relaxed ); } 231void native_router_top10 (const float * logits ,int32_t * ids ,float * weights ,void * stream ) { 232if (!stream || !valid (logits ,512 * 4 )|| !valid (ids ,10 * 4 )|| !valid (weights ,10 * 4 ) 233|| overlap (logits ,512 * 4 ,ids ,10 * 4 )|| overlap (logits ,512 * 4 ,weights ,10 * 4 ) 234|| overlap (ids ,10 * 4 ,weights ,10 * 4 )) 235throw std::invalid_argument ("native router requires a stream, aligned spans, and disjoint outputs" ); 236 { 237auto exp_props = sycl::ext::oneapi::experimental::properties { 238 sycl::ext::oneapi::experimental::use_root_sync }; 239 240 strata::kprof::kp (strata::q_of (stream ),__FILE__ ,__func__ ,__LINE__ ) 241-> template parallel_for < dpct_kernel_name < class route_96e6fb >> ( 242 sycl::nd_range < 3 > (sycl::range (1 ,8 ,32 ), sycl::range (1 ,8 ,32 )), 243exp_props , 244 [= ](sycl::nd_item < 3 > item_ct1 ) 245 [[sycl ::reqd_sub_group_size (32 )]] { 246route < 512 > (logits ,ids ,weights ); 247 }); 248 } 249/* 250DPCT1010: SYCL uses exceptions to report errors and does not use the 251error codes. The cudaGetLastError function call was replaced with 0. You 252need to rewrite this code. 253*/ 254const auto error = 0 ; 255/* 256DPCT1009: SYCL reports errors using exceptions and does not use error 257codes. Please replace the "get_error_string_dummy(...)" with a real 258error-handling function. 259*/ 260/* 261DPCT1001: The statement could not be removed. 262*/ 263/* 264DPCT1000: Error handling if-stmt was detected but could not be 265rewritten. 266*/ 267if (error != 2680 )throw std::runtime_error (dpct::get_error_string_dummy (error )); 269} 270void native_router_top10_multi (const float * logits ,int32_t * ids ,float * weights ,int n_tok ,void * stream ) { 271if (!stream || n_tok < 1 || !valid (logits , (size_t )n_tok * 512 * 4 )|| !valid (ids , (size_t )n_tok * 10 * 4 )|| 272 !valid (weights , (size_t )n_tok * 10 * 4 )) 273throw std::invalid_argument ("native router (multi) requires a stream and aligned [n,512]/[n,10] buffers" ); 274// SYCL port: one block per token running the single-token route<512> (the same kernel as the 256-expert multi 275// launch below). Upstream's one-warp-per-token route_multi gives the same bits (native_multi_parity checks 276// that) but hung an Arc A750 (Alchemist) on its first launch. 277 strata::kprof::kp (strata::q_of (stream ),__FILE__ ,__func__ ,__LINE__ ) 278-> template parallel_for < dpct_kernel_name < class route_512_multi >> ( 279 sycl::nd_range < 3 > (sycl::range (1 ,1 , (unsigned )n_tok )* sycl::range (1 ,8 ,32 ), sycl::range (1 ,8 ,32 )), 280 [= ](sycl::nd_item < 3 > item_ct1 ) [[sycl ::reqd_sub_group_size (32 )]] {route < 512 > (logits ,ids ,weights ); }); 281/* 282DPCT1010: SYCL uses exceptions to report errors and does not use the 283error codes. The cudaGetLastError function call was replaced with 0. You 284need to rewrite this code. 285*/ 286const auto error = 0 ; 287/* 288DPCT1009: SYCL reports errors using exceptions and does not use error 289codes. Please replace the "get_error_string_dummy(...)" with a real 290error-handling function. 291*/ 292/* 293DPCT1001: The statement could not be removed. 294*/ 295/* 296DPCT1000: Error handling if-stmt was detected but could not be 297rewritten. 298*/ 299if (error != 3000 )throw std::runtime_error (dpct::get_error_string_dummy (error )); 301} 302 303void native_router_top10_multi_ne (const float * logits ,int32_t * ids ,float * weights ,int n_tok ,int n_expert ,void * stream ) { 304if (n_expert == 512 ) {native_router_top10_multi (logits ,ids ,weights ,n_tok ,stream );return ; } 305if (!stream || n_tok < 1 || n_expert != 256 || !valid (logits , (size_t )n_tok * 256 * 4 )|| !valid (ids , (size_t )n_tok * 10 * 4 )|| 306 !valid (weights , (size_t )n_tok * 10 * 4 )) 307throw std::invalid_argument ("native router (multi, 256): a stream, 256 experts and aligned [n,256]/[n,10] buffers" ); 308 strata::kprof::kp (strata::q_of (stream ),__FILE__ ,__func__ ,__LINE__ ) 309-> template parallel_for < dpct_kernel_name < class route_256_multi >> ( 310 sycl::nd_range < 3 > (sycl::range (1 ,1 , (unsigned )n_tok )* sycl::range (1 ,8 ,32 ), sycl::range (1 ,8 ,32 )), 311 [= ](sycl::nd_item < 3 > item_ct1 ) [[sycl ::reqd_sub_group_size (32 )]] {route < 256 > (logits ,ids ,weights ); }); 312} 313}