okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
a8a51b280
main
1#include "b60_layout_state.hpp" 2// src/kernels/cuda/shared_expert.cu - P2.S2: the shared expert. 3// 4// `ref/moe.py::shared_expert`, transcribed: 5// 6// h = silu(x @ gate_shexp.T) * (x @ up_shexp.T) <- SILU GOES ON GATE, not on up 7// h = h @ down_shexp.T (nt, n_embd) 8// g = sigmoid(x @ gate_inp_shexp) (nt,) ONE SCALAR PER TOKEN 9// return h * g[:, None] 10// 11// TWO THINGS HERE WERE BELIEVED WRONG FOR MANY ROUNDS and `docs/semantics.md` records both. SILU GOES ON THE 12// GATE TENSOR: the opposite reading is plausible, produces the right shapes, and is wrong. And 13// `ffn_gate_inp_shexp` is `(n_embd,)` whose output is "one value per token" - a SCALAR gate obtained by dotting 14// that vector with the hidden state, NOT a per-expert gate and NOT a per-dimension elementwise one. Both were 15// live readings of the same shapes until the source comment settled them. 16// 17// The result is ADDED to the routed output - not router-weighted, not renormalised against it. 18// 19// The legacy canonical projections use their explicit Q8_0/Q8_K activation images. The optional native 20// BF16 path affects only the scalar gate: it reads the original F32 input and uses pinned CUDA MMVF plus 21// an FP32 sigmoid. Native projection overrides independently select CUDA Q8_1 MMVQ and FP32 SwiGLU. 22#define DPCT_PROFILING_ENABLED 23#include <sycl/sycl.hpp> 24#include "strata/kprof.hpp" 25#include <dpct/dpct.hpp> 26#include "strata/sycl_queue.hpp" 27#include "strata/kernels/shared_expert.hpp" 28#include "strata/kernels/bf16_gemv.hpp" 29#include "strata/kernels/bf16_bits.hpp" 30#include "strata/kernels/f16_bits.hpp" 31#include "strata/kernels/quantize_act.hpp" 32#include "strata/kernels/s2_gemv_q8.hpp" 33#include "strata/kernels/s_gemv.hpp" 34#include "strata/kernels/native_mmvq.hpp" 35 36#include <cmath> 37#include <climits> 38#include <cstdio> 39#include <string> 40#include <cstdlib> 41#include <cstring> 42#include <stdexcept> 43 44namespace strata::kernels { 45namespace { 46 47constexpr int THREADS = 128 ; 48bool native_bf16 = false; 49 50// `f32_to_f16` used to live here as a private copy. Round 198 found it - and the identical one in 51// `quantize_act.cu` - returning a NaN for every FINITE value that overflows fp16 (1e30, 65536, 1e45) instead 52// of saturating to inf, because `exp >= 31` conflates an f32 inf/NaN with an out-of-range finite exponent. 53// This file's fixture is all O(1), so it could not see it. The conversion now lives in one place, with the 54// regimes spelled out. 55 56// silu(x) = x / (1 + exp(-x)), written as `ref/moe.py` writes it, in DOUBLE then cast - the reference works in 57// float64 and a float32 exp differs in the last bits. The multiplication by `up` is the reference's order. 58__dpct_inline__ void swiglu_kernel (const float * __restrict__gate , 59const float * __restrict__up , 60float * __restrict__out ,int n ) { 61auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item < 3 > (); 62const int i = item_ct1 .get_group (2 )* item_ct1 .get_local_range (2 )+ 63item_ct1 .get_local_id (2 ); 64if (i >=n )return ; 65const double x = (double )gate [i ]; 66out [i ]= (float )(x / (1.0 + sycl::exp (- x )))* up [i ]; 67} 68 69__dpct_inline__ void native_swiglu_kernel (const float * gate ,const float * up , 70float * out ,int n ) { 71auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item < 3 > (); 72const int i = item_ct1 .get_group (2 )* item_ct1 .get_local_range (2 )+ 73item_ct1 .get_local_id (2 ); 74if (i >=n )return ; 75// Pinned CUDA unary.cuh op_silu, then unary_gated_op_kernel's multiply. 76// Explicit intrinsics reproduce its --use_fast_math operations without 77// changing compilation of the default legacy arithmetic in this file. 78out [i ]= gate [i ] / (1.0f + sycl::native::exp (- gate [i ]))* up [i ]; 79} 80 81 82void to_f16_kernel (const float * __restrict__in ,uint16_t * __restrict__out ,int n ) { 83auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item < 3 > (); 84const int i = item_ct1 .get_group (2 )* item_ct1 .get_local_range (2 )+ 85item_ct1 .get_local_id (2 ); 86if (i < n )out [i ]= f16_from_f32 (in [i ]); 87} 88 89// The per-token scalar gate: sigmoid(dot(x, w)) with w = `ffn_gate_inp_shexp` (n_embd,). 90// 91// **ONE THREAD WAS THE LARGEST SINGLE KERNEL IN THE MODEL, AND THE COMMENT DEFENDING IT SAID WHY IT SHOULD 92// NOT BE.** It read: "n_embd is 2560, so this is a short serial loop and the parallelism is elsewhere." 93// 2560 iterations is not short when each one is a DOUBLE multiply-add. This card's double rate is **1/64** of 94// its float rate, so the loop is a 2560-long dependency chain through a 1/64-rate unit - tens of microseconds 95// from the chain alone, before counting 2560 sequential global loads issued by one thread with no coalescing. 96// 97// MEASURED, and this is what the number looks like from outside: `shared_expert` is **0.2374 ms of a 98// 0.8883 ms block - 26.7% of the whole block, 11.4 ms per token** - for three projections that read 5.5 MB and 99// whose memory floor is 0.009 ms. It is seven kernels, and six of them are GEMVs or elementwise passes over 100// 640-2560 elements. This is the one that cannot be explained by bandwidth. 101// 102// THE DOUBLE ACCUMULATOR IS KEPT. `ref/gr.py` reduces in float64 and `block_sum` in `gr.cu` exists for the 103// same reason - the summation order of a tree is not the reference's, so the defence is enough precision that 104// the order stops mattering. What changes is the CHAIN: ten terms per thread instead of 2560, then a 105// tree-reduce. Through a sigmoid, a 1e-16 relative difference in the dot is not a difference. 106// 107// **BOTH OPERANDS ARE BF16, AND THAT IS THE REFERENCE'S CONTRACT, NOT A STORAGE DETAIL.** `gate_inp_shexp` is a 108// BF16 weight, so ggml converts the activation to its `vec_dot_type` - BF16 - exactly as it does for the router 109// (`docs/activation-contract.md`). This kernel used to take `const float* w` while the LOADER had already 110// re-rounded the tensor to 2 B/elem, so it read 2560 floats out of a 5120-byte buffer: 5120 B past the end of 111// the tensor, inside the 4.5 GiB arena, where nothing faults. The dot came out astronomically large, sigmoid 112// saturated to 1.0, and `scale_kernel` multiplied the shared expert's output by it - which is why the FIRST 113// symptom was 2560 non-finite outputs rather than a wrong scalar. 114// 115// A wrong scalar here is the quiet failure mode: sigmoid bounds the damage to [0,1], so a gate that should be 116// 0.5 and reads 1.0 scales the shared expert by 2x and produces perfectly finite, perfectly plausible logits. 117__dpct_inline__ double warp_sum_d (double v ) { 118/* 119DPCT1108: '__shfl_down_sync' was migrated with the experimental feature 120masked sub_group function which may not be supported by all compilers or 121runtimes. You may need to adjust the code. 122*/ 123/* 124DPCT1121: Make sure that the "v" which is used in the SYCL group 125function/algorithm is initialized. 126*/ 127#pragma unroll 128for (int off = 16 ;off > 0 ;off >>=1 )v += 129 dpct::experimental::shift_sub_group_left ( 1300xFFFFFFFFu , sycl::ext::oneapi::this_work_item::get_sub_group (),v , 131off ); 132/* 133DPCT1108: '__shfl_sync' was migrated with the experimental feature 134masked sub_group function which may not be supported by all compilers or 135runtimes. You may need to adjust the code. 136*/ 137/* 138DPCT1121: Make sure that the "v" which is used in the SYCL group 139function/algorithm is initialized. 140*/ 141return dpct::experimental::select_from_sub_group ( 1420xFFFFFFFFu , sycl::ext::oneapi::this_work_item::get_sub_group (),v ,0 ); 143} 144 145__dpct_inline__ void scalar_gate_kernel (const uint16_t * __restrict__x_bf16 , 146const uint16_t * __restrict__w_bf16 , 147float * __restrict__out ,int n_embd ) { 148auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item < 3 > (); 149auto & scratch = * sycl::ext::oneapi::group_local_memory_for_overwrite < double [8 ]> ( 150 sycl::ext::oneapi::this_work_item::get_work_group < 1513 > ());// 8 warps: the launch is <<<1, 256>>> 152double acc = 0.0 ; 153#pragma unroll 154for (int i = item_ct1 .get_local_id (2 );i < n_embd ; 155i += item_ct1 .get_local_range (2 )) 156acc += (double )f32_from_bf16 (x_bf16 [i ])* (double )f32_from_bf16 (w_bf16 [i ]); 157item_ct1 .barrier (sycl::access::fence_space::local_space ); 158const int lane = item_ct1 .get_local_id (2 )& 31 , 159warp = item_ct1 .get_local_id (2 ) >>5 ; 160acc = warp_sum_d (acc ); 161if (lane == 0 )scratch [warp ]= acc ; 162item_ct1 .barrier (sycl::access::fence_space::local_space ); 163const int nw = ((int )item_ct1 .get_local_range (2 )+ 31 ) >>5 ; 164if (warp == 0 ) { 165acc = (item_ct1 .get_local_id (2 )< nw ) 166 ?scratch [item_ct1 .get_local_id (2 )] 167 :0.0 ; 168acc = warp_sum_d (acc ); 169if (item_ct1 .get_local_id (2 )== 0 )out [0 ]= 170 (float )(1.0 / (1.0 + sycl::exp (- acc ))); 171 } 172} 173 174__dpct_inline__ void scale_kernel (float * __restrict__out , 175const float * __restrict__g ,int n ) { 176auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item < 3 > (); 177const int i = item_ct1 .get_group (2 )* item_ct1 .get_local_range (2 )+ 178item_ct1 .get_local_id (2 ); 179if (i < n )out [i ] *=g [0 ]; 180} 181 182__dpct_inline__ void native_scalar_sigmoid_kernel (float * gate ) { 183// Match the single-token CUDA sigmoid's FP32 fast-math operations without changing legacy kernels' 184// compilation flags. The dot product was already reduced by the pinned native MMVF implementation. 185gate [0 ]= 1.0f / (1.0f + sycl::native::exp (- gate [0 ])); 186} 187void native_scalar_sigmoid_multi_kernel (float * gate ) {// thread t = token t, same expression 188/* 189DPCT1064: Migrated __expf call is used in a macro/template definition 190and may not be valid for all macro/template uses. Adjust the code. 191*/ 192auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item < 3 > (); 193gate [item_ct1 .get_local_id (2 )]= 1941.0f / (1.0f + sycl::native::exp (- gate [item_ct1 .get_local_id (2 )])); 195} 196 197/// The MoE block's final combination. See the header for the two readings it exists to pin. 198__dpct_inline__ void moe_combine_kernel (const float * __restrict__parts , 199const float * __restrict__weights , 200const float * __restrict__shared , 201float * __restrict__y ,int n_embd , 202int k ,int has_shared ) { 203auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item < 3 > (); 204const int j = item_ct1 .get_group (2 )* item_ct1 .get_local_range (2 )+ 205item_ct1 .get_local_id (2 ); 206if (j >=n_embd )return ; 207// Accumulate in DOUBLE, in the reference's own order (`for i in range(k): out[t] += w[t,i] * g[0]`). 208// f32 would be defensible for ten terms, but the reference is float64 and this is one line. 209double acc = 0.0 ; 210#pragma unroll 211for (int e = 0 ;e < k ;++ e )acc += 212 (double )weights [e ]* (double )parts [(size_t )e * n_embd + j ]; 213// The SHARED output is added PLAIN - not router-weighted, not renormalised against the routed sum. 214if (has_shared )acc += (double )shared [j ]; 215y [j ]= (float )acc ; 216} 217 218}// namespace 219 220void shared_expert_set_native_bf16 (bool enabled ) {native_bf16 = enabled ; } 221bool shared_expert_native_bf16_enabled () {return native_bf16 ; } 222 223namespace { 224__dpct_inline__ void scale_rows_kernel (float * __restrict__out , 225const float * __restrict__g ,int n ) { 226auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item < 3 > (); 227const int t = item_ct1 .get_group (1 ); 228const int i = item_ct1 .get_group (2 )* item_ct1 .get_local_range (2 )+ 229item_ct1 .get_local_id (2 ); 230if (i < n )out [(size_t )t * n + i ] *=g [t ]; 231} 232 233__dpct_inline__ void sigmoid_scale_rows_kernel (float * __restrict__out , 234const float * __restrict__g , 235int n ) { 236auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item < 3 > (); 237const int t = item_ct1 .get_group (1 ); 238const int i = item_ct1 .get_group (2 )* item_ct1 .get_local_range (2 )+ 239item_ct1 .get_local_id (2 ); 240if (i < n ) { 241const float gt = 1.0f / (1.0f + sycl::native::exp (- g [t ])); 242out [(size_t )t * n + i ] *=gt ; 243 } 244} 245 246__dpct_inline__ void 247sigmoid_scale_rows_vec4_kernel (sycl::float4 * __restrict__out4 , 248const float * __restrict__g ,int n4 ) { 249auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item < 3 > (); 250const int t = item_ct1 .get_group (1 ); 251const int i = item_ct1 .get_group (2 )* item_ct1 .get_local_range (2 )+ 252item_ct1 .get_local_id (2 ); 253if (i < n4 ) { 254/* 255DPCT1098: The '*' expression is used instead of the __ldg call. 256These two expressions do not provide the exact same functionality. Check 257the generated code for potential precision and/or performance issues. 258*/ 259const float gt = 1.0f / (1.0f + sycl::native::exp (-* (g + t ))); 260 sycl::float4 v = out4 [(size_t )t * n4 + i ]; 261v .x () *=gt ; 262v .y () *=gt ; 263v .z () *=gt ; 264v .w () *=gt ; 265out4 [(size_t )t * n4 + i ]= v ; 266 } 267} 268 269void launch_sigmoid_scale_rows (float * out ,const float * g ,int n_embd , 270int n_tok , dpct::queue_ptr cs ) { 271if ((n_embd & 3 )== 0 && ((uintptr_t )out & 15u )== 0 ) { 272const int n4 = n_embd >>2 ; 273 { 274auto exp_props = sycl::ext::oneapi::experimental::properties { 275 sycl::ext::oneapi::experimental::use_root_sync }; 276 277 strata::kprof::kp (cs ,__FILE__ ,__func__ ,__LINE__ )-> template parallel_for < 278dpct_kernel_name < class sigmoid_scale_rows_vec4_kernel_723a94 >> ( 279 sycl::nd_range < 3 > ( 280 sycl::range (1 , (unsigned )n_tok , 281 (unsigned )((n4 + THREADS - 1 ) /THREADS ))* 282 sycl::range (1 ,1 ,THREADS ), 283 sycl::range (1 ,1 ,THREADS )), 284exp_props , [= ](sycl::nd_item < 3 > item_ct1 ) { 285sigmoid_scale_rows_vec4_kernel ( 286reinterpret_cast < sycl::float4 *> (out ),g ,n4 ); 287 }); 288 } 289 }else { 290auto exp_props = sycl::ext::oneapi::experimental::properties { 291 sycl::ext::oneapi::experimental::use_root_sync }; 292 293 strata::kprof::kp (cs ,__FILE__ ,__func__ ,__LINE__ )-> template parallel_for < 294dpct_kernel_name < class sigmoid_scale_rows_kernel_26f4a0 >> ( 295 sycl::nd_range < 3 > ( 296 sycl::range (1 , (unsigned )n_tok , 297 (unsigned )((n_embd + THREADS - 1 ) /THREADS ))* 298 sycl::range (1 ,1 ,THREADS ), 299 sycl::range (1 ,1 ,THREADS )), 300exp_props , [= ](sycl::nd_item < 3 > item_ct1 ) { 301sigmoid_scale_rows_kernel (out ,g ,n_embd ); 302 }); 303 } 304} 305 306bool fused_swiglu_q81_enabled () { 307static const bool on = [] { 308const char * v = std::getenv ("STRATA_FUSED_SWIGLU_Q81" ); 309return v == nullptr || std::atoi (v )!= 0 ; 310 }(); 311return on ; 312} 313}// namespace 314 315void shared_expert_multi (int n_tok ,const float * x ,const uint16_t * x_bf16 ,const NativeSharedWeights & nw , 316const uint16_t * gate_inp_bf16 ,float * gate ,float * up ,float * g ,float * out ,int64_t n_embd , 317int64_t n_ff ,void * stream ,const void * x_q8_1_ready ,int lfuse ) { 318const bool gate_deferred = (lfuse & 1 )!= 0 ,pair = (lfuse & 2 )!= 0 ; 319if (n_tok < 1 || n_tok > 8 || !nw .q8_1 || !nw .gate_data || !nw .up_data || !nw .down_data || !stream ) 320throw std::invalid_argument ("shared_expert_multi: needs 1..8 tokens, native weights, scratch and a stream" ); 321 dpct::queue_ptr cs = strata::q_of (stream ); 322// the activation's q8_1: the caller's (STRATA_VERIFY_QDEDUP, x_q8_1_ready) or the descriptor's, else quantized here 323const void * x_q8_1 = x_q8_1_ready ?x_q8_1_ready :nw .x_q8_1 ; 324if (!x_q8_1 ) { 325native_quantize_q8_1 (x ,nw .q8_1 , (int )n_embd ,n_tok ,stream ); 326x_q8_1 = nw .q8_1 ; 327 } 328// S26 STRATA_LFUSE (gate_deferred): gate and up in one launch where the pair applies (bitwise the two calls) 329if (!(pair && nw .gate_type == nw .up_type && 330native_mmvq_pair (nw .gate_type ,nw .gate_data ,nw .up_data ,x_q8_1 ,gate ,up , (int )n_embd , (int )n_ff ,n_tok ,stream ))) { 331native_mmvq (nw .gate_type ,nw .gate_data ,x_q8_1 ,gate , (int )n_embd , (int )n_ff ,n_tok ,stream ); 332native_mmvq (nw .up_type ,nw .up_data ,x_q8_1 ,up , (int )n_embd , (int )n_ff ,n_tok ,stream ); 333 } 334const int n = (int ) (n_ff * n_tok ); 335if (fused_swiglu_q81_enabled ()) { 336native_swiglu_quantize_q8_1 (gate ,up ,nw .q8_1 , (int )n_ff ,n_tok ,stream ); 337 }else { 338 { 339auto exp_props = sycl::ext::oneapi::experimental::properties { 340 sycl::ext::oneapi::experimental::use_root_sync }; 341 342 strata::kprof::kp (cs ,__FILE__ ,__func__ ,__LINE__ )-> template parallel_for < 343dpct_kernel_name < class native_swiglu_kernel_c4e755 >> ( 344 sycl::nd_range < 3 > ( 345 sycl::range (1 ,1 , (unsigned )((n + THREADS - 1 ) /THREADS ))* 346 sycl::range (1 ,1 ,THREADS ), 347 sycl::range (1 ,1 ,THREADS )), 348exp_props , [= ](sycl::nd_item < 3 > item_ct1 ) { 349native_swiglu_kernel (gate ,up ,gate ,n ); 350 }); 351 } 352native_quantize_q8_1 (gate ,nw .q8_1 , (int )n_ff ,n_tok ,stream ); 353 } 354native_mmvq (nw .down_type ,nw .down_data ,nw .q8_1 ,out , (int )n_ff , (int )n_embd ,n_tok ,stream ); 355if (gate_deferred ) {// the caller computed g (raw) with the router and scales `out` in the combine 356/* 357DPCT1010: SYCL uses exceptions to report errors and does not use the 358error codes. The cudaGetLastError function call was replaced with 0. You 359need to rewrite this code. 360*/ 361const dpct::err0 e = 0 ; 362/* 363DPCT1009: SYCL reports errors using exceptions and does not use 364error codes. Please replace the "get_error_string_dummy(...)" with a 365real error-handling function. 366*/ 367/* 368DPCT1001: The statement could not be removed. 369*/ 370/* 371DPCT1000: Error handling if-stmt was detected but could not be 372rewritten. 373*/ 374if (e != 3750 )throw std::runtime_error (std::string ("shared_expert_multi: " )+ 376 dpct::get_error_string_dummy (e )); 377return ; 378 } 379static const bool batch = [] {const char * v = std::getenv ("STRATA_DEC_BATCH" );return v == nullptr || std::atoi (v )!= 0 ; }(); 380if (native_bf16 && batch && n_tok > 1 ) {// one gemv for all rows (outputs identical), fused sigmoid+scale 381bf16_gemv_fp32_mmvf_multi (x ,n_embd ,gate_inp_bf16 ,g ,1 ,n_embd ,1 ,n_tok ,stream ); 382launch_sigmoid_scale_rows (out ,g , (int )n_embd ,n_tok ,cs ); 383 }else if (native_bf16 && n_tok == 1 ) { 384bf16_gemv_fp32_mmvf (x ,gate_inp_bf16 ,g ,n_embd ,1 ,stream ); 385launch_sigmoid_scale_rows (out ,g , (int )n_embd ,1 ,cs ); 386 }else { 387for (int t = 0 ;t < n_tok ;++ t ) { 388if (native_bf16 ) { 389bf16_gemv_fp32_mmvf (x + (size_t )t * n_embd ,gate_inp_bf16 ,g + t ,n_embd ,1 ,stream ); 390 { 391auto exp_props = 392 sycl::ext::oneapi::experimental::properties { 393 sycl::ext::oneapi::experimental::use_root_sync }; 394 395 strata::kprof::kp (cs ,__FILE__ ,__func__ ,__LINE__ )-> submit ([& ](sycl::handler & cgh ) { 396auto g_t_ct0 = g + t ; 397 398cgh .parallel_for < dpct_kernel_name < 399class native_scalar_sigmoid_kernel_9552ea >> ( 400 sycl::nd_range < 3 > (sycl::range (1 ,1 ,1 ), 401 sycl::range (1 ,1 ,1 )), 402exp_props , [= ](sycl::nd_item < 3 > item_ct1 ) { 403native_scalar_sigmoid_kernel (g_t_ct0 ); 404 }); 405 }); 406 } 407 }else { 408auto exp_props = sycl::ext::oneapi::experimental::properties { 409 sycl::ext::oneapi::experimental::use_root_sync }; 410 dpct::has_capability_or_fail (cs -> get_device (), 411 {sycl::aspect::fp64 }); 412 413 strata::kprof::kp (cs ,__FILE__ ,__func__ ,__LINE__ )-> submit ([& ](sycl::handler & cgh ) { 414auto x_bf16_size_t_t_n_embd_ct0 = 415x_bf16 + (size_t )t * n_embd ; 416auto g_t_ct2 = g + t ; 417 418cgh .parallel_for < 419dpct_kernel_name < class scalar_gate_kernel_76bc5d >> ( 420 sycl::nd_range < 3 > (sycl::range (1 ,1 ,256 ), 421 sycl::range (1 ,1 ,256 )), 422exp_props , 423 [= ](sycl::nd_item < 3 > item_ct1 ) 424 [[sycl ::reqd_sub_group_size (32 )]] { 425scalar_gate_kernel (x_bf16_size_t_t_n_embd_ct0 , 426gate_inp_bf16 ,g_t_ct2 , 427 (int )n_embd ); 428 }); 429 }); 430 } 431 } 432 { 433auto exp_props = sycl::ext::oneapi::experimental::properties { 434 sycl::ext::oneapi::experimental::use_root_sync }; 435 436 strata::kprof::kp (cs ,__FILE__ ,__func__ ,__LINE__ )-> template parallel_for < dpct_kernel_name < class scale_rows_kernel_4f17ec >> ( 437 sycl::nd_range < 3 > ( 438 sycl::range (1 , (unsigned )n_tok , 439 (unsigned )((n_embd + THREADS - 1 ) /THREADS ))* 440 sycl::range (1 ,1 ,THREADS ), 441 sycl::range (1 ,1 ,THREADS )), 442exp_props , [= ](sycl::nd_item < 3 > item_ct1 ) { 443scale_rows_kernel (out ,g , (int )n_embd ); 444 }); 445 } 446 } 447/* 448DPCT1010: SYCL uses exceptions to report errors and does not use the 449error codes. The cudaGetLastError function call was replaced with 0. You 450need to rewrite this code. 451*/ 452const dpct::err0 e = 0 ; 453/* 454DPCT1009: SYCL reports errors using exceptions and does not use error 455codes. Please replace the "get_error_string_dummy(...)" with a real 456error-handling function. 457*/ 458/* 459DPCT1001: The statement could not be removed. 460*/ 461/* 462DPCT1000: Error handling if-stmt was detected but could not be 463rewritten. 464*/ 465if (e != 0 )throw std::runtime_error (std::string ("shared_expert_multi: " )+ 466 dpct::get_error_string_dummy (e )); 467} 468 469uint64_t shared_expert_scratch_bytes (int64_t n_ff ) { 470// gate (n_ff f32) | up (n_ff f32) | q8_0 (n_ff/32*34) | q8k (n_ff/256*292) | g (1 f32), 16-byte aligned 471const uint64_t a = ((uint64_t )n_ff * 4 + 15 )& ~15ull ; 472const uint64_t q0 = ((uint64_t ) (n_ff /32 )* 34 + 15 )& ~15ull ; 473const uint64_t qk = ((uint64_t ) (n_ff /256 )* 292 + 15 )& ~15ull ; 474return a * 2 + q0 + qk + 32 ; 475} 476 477void shared_expert (const uint8_t * x_q8_0 ,const uint8_t * x_q8k , 478const uint16_t * x_bf16 ,const SForm & gate_form , 479const uint8_t * gate_codes ,const float * gate_scales , 480const float * gate_off ,const SForm & up_form , 481const uint8_t * up_codes ,const float * up_scales , 482const float * up_off ,const SForm & down_form , 483const uint8_t * down_codes ,const float * down_scales , 484const float * down_off ,const uint16_t * gate_inp_bf16 , 485float * scratch ,float * out ,int64_t n_embd ,int64_t n_ff , 486int tpr ,void * stream ,const float * x_f32 , 487const NativeSharedWeights * native )try { 488if (n_embd <=0 || n_ff <=0 )return ; 489const bool use_native = native_bf16 ; 490const bool native_gate = native && native -> gate_data && native_mmvq_supported (native -> gate_type ); 491const bool native_up = native && native -> up_data && native_mmvq_supported (native -> up_type ); 492const bool native_down = native && native -> down_data && native_mmvq_supported (native -> down_type ); 493const bool native_projection = native_gate || native_up || native_down ; 494if ((use_native || native_gate || native_up )&& !x_f32 ) 495throw std::invalid_argument ("shared_expert native input projection requires unrounded x_f32" ); 496if (native_projection ) { 497if (!native -> q8_1 || !stream || n_embd > INT_MAX || n_ff > INT_MAX ) 498throw std::invalid_argument ("shared_expert native projections require scratch, stream and int32 dimensions" ); 499// Validate every active shape before any kernel is enqueued. 500if (native_gate )native_mmvq_weight_bytes (native -> gate_type , (int )n_embd , (int )n_ff ); 501if (native_up )native_mmvq_weight_bytes (native -> up_type , (int )n_embd , (int )n_ff ); 502if (native_down )native_mmvq_weight_bytes (native -> down_type , (int )n_ff , (int )n_embd ); 503 } 504if (scratch == nullptr ) { 505 std::fprintf (stderr ,"shared_expert: scratch is null; the caller owns it " 506"(see shared_expert_scratch_bytes)\n" ); 507 std::exit (1 ); 508 } 509// CARVED FROM THE CALLER'S SCRATCH. This used to be four `cudaMalloc`s and four `cudaFree`s per call, which 510// is illegal during stream capture AND a token-path allocation - P2.T10 forbids both. 511uint8_t * p = (uint8_t * )scratch ; 512const uint64_t a = ((uint64_t )n_ff * 4 + 15 )& ~15ull ; 513const uint64_t q0 = ((uint64_t ) (n_ff /32 )* 34 + 15 )& ~15ull ; 514const uint64_t qk = ((uint64_t ) (n_ff /256 )* 292 + 15 )& ~15ull ; 515float * gate = (float * )p ; 516float * up = (float * ) (p + a ); 517uint8_t * h_q8_0 = (uint8_t * ) (p + a * 2 ); 518uint8_t * h_q8k = (uint8_t * ) (p + a * 2 + q0 ); 519float * g = (float * ) (p + a * 2 + q0 + qk ); 520 521// WHICH ACTIVATION THIS PROJECTION WANTS, READ FROM ITS OWN FORM. See `SForm::act_kind`: the three 522// families cannot be told apart by the other fields, so the kind is carried rather than derived. 523auto gemv = [& ](const SForm & f ,const uint8_t * codes ,const float * scales ,const float * off , 524const uint8_t * act80 ,const uint8_t * actq8k ,float * y ,int64_t nin ,int64_t nout ) { 525if (f .code_bits == 2 ) { 526s2_gemv_q8 (act80 ,codes ,scales ,y ,nin ,nout ,tpr ,stream ); 527 }else if (f .act_kind == 1 ) { 528s_gemv_q8k_split (actq8k ,codes ,scales ,off ,y ,nin ,nout ,f ,stream ); 529 }else { 530s_gemv_q8_0_split (act80 ,codes ,scales ,off ,y ,nin ,nout ,f ,stream ); 531 } 532 }; 533 534const unsigned g_ff = (unsigned ) ((n_ff + THREADS - 1 ) /THREADS ); 535const unsigned g_embd = (unsigned ) ((n_embd + THREADS - 1 ) /THREADS ); 536 537// gate and up projections, then silu(gate) * up in place in `gate` 538if ((native_gate || native_up )&& !(b60_layout_requested ()&& native -> x_q8_1 && native -> x_q8_1 == native -> q8_1 )) 539native_quantize_q8_1 (x_f32 ,native -> q8_1 , (int )n_embd ,1 ,stream ); 540if (native_gate ) 541native_mmvq (native -> gate_type ,native -> gate_data ,native -> q8_1 ,gate , (int )n_embd , (int )n_ff ,1 ,stream ); 542else 543gemv (gate_form ,gate_codes ,gate_scales ,gate_off ,x_q8_0 ,x_q8k ,gate ,n_embd ,n_ff ); 544if (native_up ) 545native_mmvq (native -> up_type ,native -> up_data ,native -> q8_1 ,up , (int )n_embd , (int )n_ff ,1 ,stream ); 546else 547gemv (up_form ,up_codes ,up_scales ,up_off ,x_q8_0 ,x_q8k ,up ,n_embd ,n_ff ); 548if (native_projection && native_down && fused_swiglu_q81_enabled ()) { 549native_swiglu_quantize_q8_1 (gate ,up ,native -> q8_1 , (int )n_ff ,1 ,stream ); 550native_mmvq (native -> down_type ,native -> down_data ,native -> q8_1 ,out , (int )n_ff , (int )n_embd ,1 ,stream ); 551 }else { 552if (native_projection ) 553 { 554auto exp_props = sycl::ext::oneapi::experimental::properties { 555 sycl::ext::oneapi::experimental::use_root_sync }; 556 557 strata::kprof::kp (strata::q_of (stream ),__FILE__ ,__func__ ,__LINE__ ) 558-> template parallel_for < 559dpct_kernel_name < class native_swiglu_kernel_75dcdc >> ( 560 sycl::nd_range < 3 > (sycl::range (1 ,1 ,g_ff )* 561 sycl::range (1 ,1 ,THREADS ), 562 sycl::range (1 ,1 ,THREADS )), 563exp_props , [= ](sycl::nd_item < 3 > item_ct1 ) { 564native_swiglu_kernel (gate ,up ,gate , (int )n_ff ); 565 }); 566 }else { 567auto exp_props = sycl::ext::oneapi::experimental::properties { 568 sycl::ext::oneapi::experimental::use_root_sync }; 569 dpct::has_capability_or_fail ( 570 strata::q_of (stream )-> get_device (), 571 {sycl::aspect::fp64 }); 572 573 strata::kprof::kp (strata::q_of (stream ),__FILE__ ,__func__ ,__LINE__ ) 574-> template parallel_for < dpct_kernel_name < class swiglu_kernel_fbfcfe >> ( 575 sycl::nd_range < 3 > (sycl::range (1 ,1 ,g_ff )* 576 sycl::range (1 ,1 ,THREADS ), 577 sycl::range (1 ,1 ,THREADS )), 578exp_props , [= ](sycl::nd_item < 3 > item_ct1 ) { 579swiglu_kernel (gate ,up ,gate , (int )n_ff ); 580 }); 581 } 582 583// down: (n_ff) -> (n_embd), and THE INTERMEDIATE IS QUANTIZED TO THE DOWN WEIGHT'S OWN CONTRACT - which is 584// what `ggml_mul_mat` does for every matmul in the model. It used to be rounded to fp16 with no 585// justification beyond "the kernel takes fp16". 586if (native_down ) { 587native_quantize_q8_1 (gate ,native -> q8_1 , (int )n_ff ,1 ,stream ); 588native_mmvq (native -> down_type ,native -> down_data ,native -> q8_1 ,out , (int )n_ff , (int )n_embd ,1 ,stream ); 589 }else if (down_form .act_kind == 1 ) { 590if (n_ff %256 != 0 ) { 591 std::fprintf (stderr ,"shared_expert: the down weight wants Q8_K but n_ff %lld is not a multiple " 592"of 256; Q8_K is structurally impossible here\n" , (long long )n_ff ); 593 std::exit (1 ); 594 } 595quantize_q8_K (gate ,h_q8k ,n_ff ,stream ); 596gemv (down_form ,down_codes ,down_scales ,down_off ,h_q8_0 ,h_q8k ,out ,n_ff ,n_embd ); 597 }else if (down_form .code_bits == 2 ) { 598quantize_q8_0 (gate ,h_q8_0 ,n_ff ,stream ); 599gemv (down_form ,down_codes ,down_scales ,down_off ,h_q8_0 ,h_q8k ,out ,n_ff ,n_embd ); 600 }else { 601quantize_q8_0 (gate ,h_q8_0 ,n_ff ,stream ); 602gemv (down_form ,down_codes ,down_scales ,down_off ,h_q8_0 ,h_q8k ,out ,n_ff ,n_embd ); 603 } 604 } 605 606// the per-token scalar gate, then the multiply. Note the gate is computed from `x`, the ORIGINAL hidden 607// state, not from anything the expert produced. The historical branch uses BF16-rounded inputs; the 608// native branch uses the pinned CUDA FP32 activation contract. 609// `<<<1, 256>>>`: one block, because the output is ONE scalar and a second block would only add a global 610// round trip. 256 threads is the reduction's width, not the problem's size. 611if (use_native ) { 612bf16_gemv_fp32_mmvf (x_f32 ,gate_inp_bf16 ,g ,n_embd ,1 ,stream ); 613launch_sigmoid_scale_rows (out ,g , (int )n_embd ,1 , 614 strata::q_of (stream )); 615 }else { 616 { 617auto exp_props = sycl::ext::oneapi::experimental::properties { 618 sycl::ext::oneapi::experimental::use_root_sync }; 619 dpct::has_capability_or_fail ( 620 strata::q_of (stream )-> get_device (), 621 {sycl::aspect::fp64 }); 622 623 strata::kprof::kp (strata::q_of (stream ),__FILE__ ,__func__ ,__LINE__ ) 624-> template parallel_for < 625dpct_kernel_name < class scalar_gate_kernel_82de77 >> ( 626 sycl::nd_range < 3 > (sycl::range (1 ,1 ,256 ), 627 sycl::range (1 ,1 ,256 )), 628exp_props , 629 [= ](sycl::nd_item < 3 > item_ct1 ) 630 [[sycl ::reqd_sub_group_size (32 )]] { 631scalar_gate_kernel (x_bf16 ,gate_inp_bf16 ,g , 632 (int )n_embd ); 633 }); 634 } 635 { 636auto exp_props = sycl::ext::oneapi::experimental::properties { 637 sycl::ext::oneapi::experimental::use_root_sync }; 638 639 strata::kprof::kp (strata::q_of (stream ),__FILE__ ,__func__ ,__LINE__ ) 640-> template parallel_for < dpct_kernel_name < class scale_kernel_a41a71 >> ( 641 sycl::nd_range < 3 > (sycl::range (1 ,1 ,g_embd )* 642 sycl::range (1 ,1 ,THREADS ), 643 sycl::range (1 ,1 ,THREADS )), 644exp_props , [= ](sycl::nd_item < 3 > item_ct1 ) { 645scale_kernel (out ,g , (int )n_embd ); 646 }); 647 } 648 } 649 650if (stream == nullptr ) { 651const dpct::err0 e = DPCT_CHECK_ERROR ( 652 dpct::get_current_device ().queues_wait_and_throw ()); 653 } 654} 655catch (sycl::exception const & exc ) { 656 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 657 <<", line:" <<__LINE__ << std::endl ; 658 std::exit (1 ); 659} 660 661void moe_combine (const float * parts ,const float * weights ,const float * shared , 662float * y ,int64_t n_embd ,int64_t k ,void * stream )try { 663if (n_embd <=0 || k <=0 )return ; 664// k > 64 is refused rather than truncated: silently summing the first 64 of a longer list would be a 665// wrong answer that looks like a right one, and no geometry in this artifact comes close to it. 666if (k > 64 ) { 667 std::fprintf (stderr ,"moe_combine: k = %lld exceeds 64\n" , (long long )k ); 668 std::exit (1 ); 669 } 670const unsigned grid = (unsigned ) ((n_embd + THREADS - 1 ) /THREADS ); 671 { 672auto exp_props = sycl::ext::oneapi::experimental::properties { 673 sycl::ext::oneapi::experimental::use_root_sync }; 674 dpct::has_capability_or_fail ( 675 strata::q_of (stream )-> get_device (), 676 {sycl::aspect::fp64 }); 677 678 strata::kprof::kp (strata::q_of (stream ),__FILE__ ,__func__ ,__LINE__ ) 679-> submit ([& ](sycl::handler & cgh ) { 680int shared_nullptr_ct6 = shared != nullptr ; 681 682cgh .parallel_for < 683dpct_kernel_name < class moe_combine_kernel_c03916 >> ( 684 sycl::nd_range < 3 > (sycl::range (1 ,1 ,grid )* 685 sycl::range (1 ,1 ,THREADS ), 686 sycl::range (1 ,1 ,THREADS )), 687exp_props , [= ](sycl::nd_item < 3 > item_ct1 ) { 688moe_combine_kernel (parts ,weights ,shared ,y , 689 (int )n_embd , (int )k , 690shared_nullptr_ct6 ); 691 }); 692 }); 693 } 694if (stream == nullptr ) { 695const dpct::err0 e = DPCT_CHECK_ERROR ( 696 dpct::get_current_device ().queues_wait_and_throw ()); 697 } 698} 699catch (sycl::exception const & exc ) { 700 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 701 <<", line:" <<__LINE__ << std::endl ; 702 std::exit (1 ); 703} 704 705}// namespace strata::kernels