okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
86bed1c92
main
1// src/kernels/cuda/gr.cu - P2.S2: the gated residual / hyper-connection, `gr_read` and `gr_write`. 2// 3// See include/strata/kernels/gr.hpp for the semantics, for why the weights are bf16, and for the history of 4// this kernel's 134x-off-the-floor first version. The short form: it was launched `<<<1, 256>>>` so that 5// `xn`/`xq` fit in shared memory, which used ONE of 48 SMs and cost 262 ms/token. 6// 7// THE SHAPE OF THE FIX is that each projection is an ordinary GEMV and is now mapped the way the shapes want: 8// 9// norm hc blocks, one per residual stream (each needs its own reduction) 10// down ONE WARP PER OUTPUT ROW, lanes stride the 10240 reduction axis 11// gate ONE WARP PER OUTPUT ROW, lanes stride the 320 reduction axis 12// mean a flat elementwise pass over n_embd 13// 14// WARP-PER-ROW RATHER THAN THREAD-PER-ROW, and that is the whole difference. A thread walking one row is 15// coalesced with ITSELF and 32 transactions away from its warp neighbours: `w_down[k*hc_dim + i]` for fixed k 16// is contiguous, but two threads on rows k and k+1 are hc_dim*2 bytes apart. With the warp on one row, lanes 17// i, i+1, i+2 touch consecutive addresses in EITHER orientation - which is why this version needs no 18// transposed copies and takes both matrices exactly as the manifest stores them. 19// 20// Layouts are the MANIFEST's: `hc_attn_down.weight` is [10240, 320] with ne0 = hc*n_embd fast, so it holds 21// `w_down[k][i]` with i contiguous - `ref/gr.py`'s (hc_lr, hc*n_embd) row-major. `hc_attn_up.weight` is 22// [320, 10240] so it holds `w_up[i][k]` with k contiguous - `ref/gr.py`'s (hc*n_embd, hc_lr) row-major. Both 23// index with no permutation at all. 24#define DPCT_PROFILING_ENABLED 25#include <sycl/sycl.hpp> 26#include "strata/kprof.hpp" 27#include <dpct/dpct.hpp> 28#include "strata/sycl_queue.hpp" 29#include "strata/kernels/gr.hpp" 30#include "strata/kernels/bf16_bits.hpp" 31#include "strata/kernels/bf16_gemv.hpp" 32#include "strata/kernels/native_gr_norm.hpp" 33#include "strata/kernels/native_gr_postops.hpp" 34 35#include <cmath> 36#include <cstdio> 37#include <cstdlib> 38#include <cstring> 39#include <stdexcept> 40 41namespace strata::kernels { 42namespace { 43 44constexpr int THREADS = 256 ; 45constexpr int WARPS = THREADS /32 ; 46bool fp32_activations = false; 47bool native_mmvf = false; 48 49/// The bf16 conversions live in `strata/kernels/bf16_bits.hpp`, and this file used to carry its own copies. 50/// Two files with a private copy of a conversion whose failure mode is silent wrong bits is one too many - 51/// and the reason the shared header exists is that `bf16` and `fp16` are NOT two spellings of one idea, so a 52/// routine written for one and reused for the other is wrong in a way that still produces numbers. 53/// 54/// The local names are kept as thin wrappers so the body below is untouched by the swap. 55__dpct_inline__ uint16_t f32_to_bf16_bits (float f ) {return bf16_from_f32 (f ); } 56__dpct_inline__ float bf16_bits_to_f32 (uint16_t h ) {return f32_from_bf16 (h ); } 57__dpct_inline__ float activation_f32 (float x ) {return x ; } 58__dpct_inline__ float activation_f32 (uint16_t x ) {return bf16_bits_to_f32 (x ); } 59__dpct_inline__ void store_activation (float * dst ,int i ,float x ) { 60dst [i ]= x ; 61} 62__dpct_inline__ void store_activation (uint16_t * dst ,int i ,float x ) { 63dst [i ]= f32_to_bf16_bits (x ); 64} 65 66/// silu and sigmoid exactly as `ref/gr.py` writes them - in FLOAT, not double. 67/// 68/// This is the opposite of `shared_expert.cu`, which uses double, and the difference is not stylistic: 69/// `ref/gr.py`'s arrays are float32, so `x / (1.0 + np.exp(-x))` evaluates in float32 under NEP 50, while 70/// `ref/moe.py` works in float64. Matching the reference's PRECISION is part of transcribing it. 71__dpct_inline__ float silu_f (float x ) { 72return x / (1.0f + sycl::native::exp (- x )); 73} 74__dpct_inline__ float sigmoid_f (float x ) { 75return 1.0f / (1.0f + sycl::native::exp (- x )); 76} 77 78__dpct_inline__ double warp_sum (double v ) { 79/* 80DPCT1108: '__shfl_down_sync' was migrated with the experimental feature 81masked sub_group function which may not be supported by all compilers or 82runtimes. You may need to adjust the code. 83*/ 84/* 85DPCT1121: Make sure that the "v" which is used in the SYCL group 86function/algorithm is initialized. 87*/ 88#pragma unroll 89for (int off = 16 ;off > 0 ;off >>=1 )v += 90 dpct::experimental::shift_sub_group_left ( 910xFFFFFFFFu , sycl::ext::oneapi::this_work_item::get_sub_group (),v , 92off ); 93/* 94DPCT1108: '__shfl_sync' was migrated with the experimental feature masked 95sub_group function which may not be supported by all compilers or runtimes. 96You may need to adjust the code. 97*/ 98/* 99DPCT1121: Make sure that the "v" which is used in the SYCL group 100function/algorithm is initialized. 101*/ 102return dpct::experimental::select_from_sub_group ( 1030xFFFFFFFFu , sycl::ext::oneapi::this_work_item::get_sub_group (),v ,0 ); 104} 105 106__dpct_inline__ float warp_sumf (float v ) { 107/* 108DPCT1108: '__shfl_down_sync' was migrated with the experimental feature 109masked sub_group function which may not be supported by all compilers or 110runtimes. You may need to adjust the code. 111*/ 112/* 113DPCT1121: Make sure that the "v" which is used in the SYCL group 114function/algorithm is initialized. 115*/ 116#pragma unroll 117for (int off = 16 ;off > 0 ;off >>=1 )v += 118 dpct::experimental::shift_sub_group_left ( 1190xFFFFFFFFu , sycl::ext::oneapi::this_work_item::get_sub_group (),v , 120off ); 121/* 122DPCT1108: '__shfl_sync' was migrated with the experimental feature masked 123sub_group function which may not be supported by all compilers or runtimes. 124You may need to adjust the code. 125*/ 126/* 127DPCT1121: Make sure that the "v" which is used in the SYCL group 128function/algorithm is initialized. 129*/ 130return dpct::experimental::select_from_sub_group ( 1310xFFFFFFFFu , sycl::ext::oneapi::this_work_item::get_sub_group (),v ,0 ); 132} 133 134/// The FP32 block-wide sum, for the reason the review's G5 states: this is a GeForce part and FP64 runs at a 135/// small fraction of FP32, so a `double` reduction turns a bandwidth kernel into a latency kernel. 136/// 137/// The scratch is taken as `double*` and reinterpreted as `float*` rather than changing the callers' shared 138/// arrays, because `double scratch[8]` is 64 bytes and so is at least as large as the `float[8]` this needs - 139/// the cast cannot overrun, and it keeps the change to one function instead of one per caller. 140inline float block_sumf (float v ,double * scratch_raw ) { 141auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item < 3 > (); 142float * scratch = (float * )scratch_raw ; 143// The leading barrier is not decoration - see the note on `block_sum` above: the result is read straight out 144// of `scratch[0]` by every thread and a later call reuses the array, so without it a fast thread can 145// overwrite `scratch[0]` before a slow one has read the previous result. 146/* 147DPCT1065: Consider replacing sycl::nd_item::barrier() with 148sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better 149performance if there is no access to global memory. 150*/ 151item_ct1 .barrier (); 152const int lane = item_ct1 .get_local_id (2 )& 31 , 153warp = item_ct1 .get_local_id (2 ) >>5 ; 154v = warp_sumf (v ); 155if (lane == 0 )scratch [warp ]= v ; 156/* 157DPCT1065: Consider replacing sycl::nd_item::barrier() with 158sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better 159performance if there is no access to global memory. 160*/ 161item_ct1 .barrier (); 162const int nw = ((int )item_ct1 .get_local_range (2 )+ 31 ) >>5 ; 163v = (item_ct1 .get_local_id (2 )< nw ) ?scratch [item_ct1 .get_local_id (2 )] 164 :0.0f ; 165if (warp == 0 )v = warp_sumf (v ); 166if (item_ct1 .get_local_id (2 )== 0 )scratch [0 ]= v ; 167/* 168DPCT1065: Consider replacing sycl::nd_item::barrier() with 169sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better 170performance if there is no access to global memory. 171*/ 172item_ct1 .barrier (); 173return scratch [0 ]; 174} 175 176/// Block-wide sum in DOUBLE, broadcast to every thread. 177/// 178/// Double because `ref/gr.py` reduces in float64 for the norm and the bottleneck, and because a block-wide 179/// f32 sum of 2560 squares is a different number from the reference's; the shuffle tree here also reorders 180/// the additions, so the only defence is enough precision that the order stops mattering. 181/// 182/// The leading `__syncthreads()` is not decoration: the result is read straight out of `scratch[0]` by every 183/// thread, and a later call reuses the same array. Without a barrier on entry a fast thread can overwrite 184/// `scratch[0]` before a slow one has read the previous result - a race that is invisible in most runs. 185double block_sum (double v ,double * scratch ) { 186/* 187DPCT1065: Consider replacing sycl::nd_item::barrier() with 188sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better 189performance if there is no access to global memory. 190*/ 191auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item < 3 > (); 192item_ct1 .barrier (); 193const int lane = item_ct1 .get_local_id (2 )& 31 , 194warp = item_ct1 .get_local_id (2 ) >>5 ; 195v = warp_sum (v ); 196if (lane == 0 )scratch [warp ]= v ; 197/* 198DPCT1065: Consider replacing sycl::nd_item::barrier() with 199sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better 200performance if there is no access to global memory. 201*/ 202item_ct1 .barrier (); 203const int nw = ((int )item_ct1 .get_local_range (2 )+ 31 ) >>5 ; 204v = (item_ct1 .get_local_id (2 )< nw ) ?scratch [item_ct1 .get_local_id (2 )] 205 :0.0 ; 206if (warp == 0 )v = warp_sum (v ); 207if (item_ct1 .get_local_id (2 )== 0 )scratch [0 ]= v ; 208/* 209DPCT1065: Consider replacing sycl::nd_item::barrier() with 210sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better 211performance if there is no access to global memory. 212*/ 213item_ct1 .barrier (); 214return scratch [0 ]; 215} 216 217/// `hc` blocks, one per residual stream: per-stream RMSNorm, then the activated stream in both forms. 218/// 219/// ggml_rms_norm reduces over ne[0], and ne[0] is n_embd, so the reduction is PER STREAM. The `[n_embd, hc]` 220/// gamma then scales each stream individually. 221/// 222/// A per-thread accumulator is only a sum when the block is narrower than the row, which is why this is a 223/// block reduction: with `n_embd` equal to the thread count every thread would hold exactly one element and 224/// normalise by its own square. That mistake is silent - it produces a plausible vector of the right shape - 225/// and it is what `gr_parity`'s `mixed vs reference` caught at 2.0e+01 in round 196. 226template < bool FP32_ACT > 227__dpct_inline__ void gr_norm_kernel (const float * __restrict__R , 228const float * __restrict__w_norm ,float eps , 229int n_embd ,float * __restrict__xn , 230uint16_t * __restrict__xq ) { 231auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item < 3 > (); 232auto & scratch = * sycl::ext::oneapi::group_local_memory_for_overwrite < double [8 ]> ( 233 sycl::ext::oneapi::this_work_item::get_work_group < 3 > ()); 234const int c = item_ct1 .get_group (2 ); 235const float * Rc = R + (size_t )c * n_embd ; 236float * xnc = xn + (size_t )c * n_embd ; 237uint16_t * xqc = xq + (size_t )c * n_embd ; 238 239// FP32, for the same reason as `gr_down_kernel` and `gr_inject_kernel`: this is a GeForce part, FP64 runs 240// at a small fraction of FP32, and the sum of squares is a pure reduction. It was the last `double` on the 241// `gr_read` path. `gr_norm` is only 0.80 ms/token, so this is hygiene rather than a headline - but it is 242// 12 of the FP64 sites the review's G5 counted in this file, and the rule it states ("no FP64 on any decode 243// or prefill path") is worth being able to check mechanically rather than case by case. 244float ss = 0.0f ; 245for (int d = item_ct1 .get_local_id (2 );d < n_embd ; 246d += item_ct1 .get_local_range (2 )) { 247const float v = Rc [d ]; 248ss += v * v ; 249 } 250const float ms = block_sumf (ss ,scratch ) / (float )n_embd ; 251const float rs = sycl::rsqrt (ms + eps ); 252for (int d = item_ct1 .get_local_id (2 );d < n_embd ; 253d += item_ct1 .get_local_range (2 )) { 254const float x = Rc [d ]* rs * w_norm [(size_t )c * n_embd + d ]; 255xnc [d ]= x ; 256if constexpr (!FP32_ACT )xqc [d ]= f32_to_bf16_bits (x ); 257 } 258} 259 260/// `lo = silu((bf16(xn) @ w_down.T) / hc)`, ONE BLOCK PER OUTPUT ROW with its warps splitting the reduction. 261template < typename Activation > 262__dpct_inline__ void gr_down_kernel (const Activation * __restrict__xq , 263const uint16_t * __restrict__w_down , 264int hc_dim ,int hc_lr ,int hc , 265Activation * __restrict__lq ) { 266auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item < 3 > (); 267const int k = item_ct1 .get_group (2 ); 268if (k >=hc_lr )return ; 269const int lane = item_ct1 .get_local_id (2 )& 31 ; 270const int warp = item_ct1 .get_local_id (2 ) >>5 ; 271const int nw = (int )(item_ct1 .get_local_range (2 ) >> 2725 );// warps per row == warps per block 273const uint16_t * row = w_down + (size_t )k * hc_dim ; 274// **THE OCCUPANCY HERE IS 10% AND IT IS REAL, BUT FIXING IT DOES NOT PAY.** `hc_lr` is 320, one warp per 275// row, 8 warps per block, so this launches 40 blocks = 320 warps: **6.7 warps per SM out of the 64 a 276// Blackwell SM holds**, each lane walking 10,240 elements in 320 dependent steps. 277// 278// Four independent accumulators were tried to break the dependency chain and put four loads in flight per 279// lane. **Measured: 39.86 ms/token of pure GPU against 39.80, i.e. no change**, with `gr_parity` green 280// either way. Removed, on the rule this file already states about `#pragma unroll 4`: a hint that does not 281// change the timing is a claim that is not true. 282// 283// The reason is that `gr_read`'s cost is not here. Its four kernels are the norm (4 blocks), this (40), 284// `gr_gate_kernel` (1,280) and the mean (10), and the 1,280-block gate kernel reads 6.55 MB of weights with 285// good occupancy - so `gr_read`'s ~93 us is mostly the gate kernel at its own memory rate, and the ~165 GB/s 286// whole-call figure is an average over kernels that do not share a rate. 287// **FP32, AND THE FP64 THAT WAS HERE COST MORE THAN EVERYTHING ELSE IN `gr_read`.** 288// 289// This accumulated in `double`. GeForce Blackwell executes FP64 at a small fraction of FP32 - 1/64 on 290// recent parts - so a 320-step dependent FP64 chain per lane turned a memory-bound reduction into a 291// latency-bound one. The `nsys` per-kernel table (round 2) measured it at **5.07 ms/token, 15.3% of all 292// GPU time**, against `gr_gate_kernel`'s 1.23 ms - which REFUTES the comment that used to sit here, that 293// "gr_read's ~93 us is mostly the gate kernel at its own memory rate". It was not: down + inject were 294// 8.77 of gr_read's 10.8 ms, and the gate was 1.23. 295// 296// The justification for `double` was matching `ref/gr.py`'s float64 transcription. **The ground truth is 297// llama.cpp, and llama.cpp accumulates in FP32** - so this does not move away from the oracle, it moves 298// toward it, and the review's G1 lists it first. 299// 300// Four independent accumulators were tried here BEFORE, against the FP64 version, and measured no change 301// (39.86 vs 39.80 ms/token) - because FP64 throughput was the limit, not the dependency chain. With FP32 302// the kernel becomes memory-bound: it reads ~13 MB per call across xq and w_down, which at the measured 303// 641 GB/s is ~20 us against the 52 us this took. 304// **THE OCCUPANCY CONCLUSION ABOVE IS STALE, AND THIS IS THE RETEST IT ASKED FOR.** 305// 306// "Fixing it does not pay" was measured against the FP64 version, where FP64 THROUGHPUT was the limit and 307// more parallelism could not help. The kernel is FP32 now (round 282: 5.07 -> 2.38 ms/token) and the limit 308// moved to memory - which is the regime where occupancy does pay, because at 6.7 warps/SM there are not 309// enough bytes in flight to cover DRAM latency. The old result is not wrong; it is about a different kernel. 310// 311// One BLOCK per row, its 8 warps splitting the 10,240-element reduction: 320 blocks x 8 = **2,560 warps = 312// 53 warps/SM instead of 6.7**, with no second kernel and no partial buffer - the eight partials meet in 313// shared memory. Lanes within a warp still read consecutive addresses, because warp `w` starts at 314// `w * 32` and strides by `nw * 32`. 315float acc = 0.0f ; 316#pragma unroll 317for (int i = warp * 32 + lane ;i < hc_dim ;i += nw * 32 ) 318acc += activation_f32 (xq [i ])* bf16_bits_to_f32 (row [i ]); 319acc = warp_sumf (acc ); 320 321auto & part = 322* sycl::ext::oneapi::group_local_memory_for_overwrite < float [WARPS ]> ( 323 sycl::ext::oneapi::this_work_item::get_work_group < 3 > ()); 324if (lane == 0 )part [warp ]= acc ; 325item_ct1 .barrier (sycl::access::fence_space::local_space ); 326if (warp == 0 ) { 327float t = (lane < nw ) ?part [lane ] :0.0f ; 328t = warp_sumf (t ); 329// NOTE: the reduction order differs from the one-warp version, so this is a NUMERICS CHANGE. C1 is the 330// gate that judges it - not this comment, and not `gr_parity`, which compares against the reference on 331// a fixture that a changed summation order can still pass. 332if (lane == 0 )store_activation (lq ,k ,silu_f (t / (float )hc )); 333 } 334} 335 336/// `gated[i] = xn[i] * sigmoid(bf16(lo) @ w_up.T)`, one warp per output row, lanes striding hc_lr. 337template < typename Activation > 338__dpct_inline__ void gr_gate_kernel (const Activation * __restrict__lq , 339const uint16_t * __restrict__w_up , 340const float * __restrict__xn ,int hc_dim , 341int hc_lr ,float * __restrict__gated ) { 342auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item < 3 > (); 343const int i = 344item_ct1 .get_group (2 )* WARPS + (item_ct1 .get_local_id (2 ) >>5 ); 345if (i >=hc_dim )return ; 346const int lane = item_ct1 .get_local_id (2 )& 31 ; 347const uint16_t * row = w_up + (size_t )i * hc_lr ; 348float acc = 0.0f ; 349#pragma unroll 350for (int k = lane ;k < hc_lr ;k += 32 ) 351acc += activation_f32 (lq [k ])* bf16_bits_to_f32 (row [k ]); 352acc = warp_sumf (acc ); 353// Every lane computes the sigmoid (the shuffle broadcasts acc), so there is no second sync point and no 354// branch; lane 0 stores. 355if (lane == 0 )gated [i ]= xn [i ]* sigmoid_f (acc ); 356} 357 358/// `mixed[d] = mean over c of gated[c][d]`. Flat elementwise: the mean is over the streams, which are 359/// strided by n_embd, so no cross-thread reduction is needed at all. 360__dpct_inline__ void gr_mean_kernel (const float * __restrict__gated ,int n_embd , 361int hc ,float * __restrict__mixed ) { 362auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item < 3 > (); 363const int d = item_ct1 .get_group (2 )* item_ct1 .get_local_range (2 )+ 364item_ct1 .get_local_id (2 ); 365if (d >=n_embd )return ; 366float m = 0.0f ; 367#pragma unroll 368for (int c = 0 ;c < hc ;++ c )m += gated [(size_t )c * n_embd + d ]; 369mixed [d ]= m / (float )hc ; 370} 371 372/// `inject[c] = bf16(xn) @ w_inject[c]`, one value per stream: ONE WARP PER STREAM, lanes striding hc_dim. 373/// 374/// This mirrors `gr_down_kernel` rather than using a block-wide reduction. `hc` is 4 at the real geometry, 375/// so a block per stream would put 256 threads on a 10240-element dot and leave the reduction to do all the 376/// work; a warp per stream is the same shape as the down projection and reuses its pattern exactly. The 377/// whole kernel is one block of `32*hc` threads, which is small - and it is a 4-value output, so it is. 378template < typename Activation > 379__dpct_inline__ void gr_inject_kernel (const Activation * __restrict__xq , 380const uint16_t * __restrict__w_inject , 381int hc_dim ,int hc , 382float * __restrict__inject ) { 383auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item < 3 > (); 384const int c = item_ct1 .get_local_id (2 ) >>5 ; 385if (c >=hc )return ; 386const int lane = item_ct1 .get_local_id (2 )& 31 ; 387const uint16_t * row = w_inject + (size_t )c * hc_dim ; 388// FP32, for the same reason as `gr_down_kernel` - and this one is worse. A ONE-BLOCK kernel doing four 389// 10,240-element FP64 reductions measured **3.70 ms/token, 11.1% of all GPU time, from a single SM out of 390// 48.** It is the fourth largest consumer of GPU time in the engine and it cannot use more than 1/48th of 391// the machine. In FP32 the same reduction is a few microseconds and the block size stops mattering. 392float acc = 0.0f ; 393#pragma unroll 394for (int i = lane ;i < hc_dim ;i += 32 ) 395acc += activation_f32 (xq [i ])* bf16_bits_to_f32 (row [i ]); 396acc = warp_sumf (acc ); 397if (lane == 0 )inject [c ]= acc ; 398} 399 400__dpct_inline__ void gr_write_kernel (const float * __restrict__R , 401const float * __restrict__block_out , 402const float * __restrict__inject , 403int n_embd ,int hc , 404float * __restrict__out , 405uint8_t * dpct_local ) { 406// w = 2*sigmoid(inject/hc), computed once per stream in shared rather than per element. 407auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item < 3 > (); 408auto smem_raw = (unsigned char * )dpct_local ; 409float * w = (float * )smem_raw ; 410if ((int )item_ct1 .get_local_id (2 )< hc )w [item_ct1 .get_local_id (2 )]= 4112.0f * sigmoid_f (inject [item_ct1 .get_local_id (2 )] / (float )hc ); 412item_ct1 .barrier (sycl::access::fence_space::local_space ); 413const long long n = (long long )hc * n_embd ; 414for (long long i = 415 (long long )item_ct1 .get_group (2 )* item_ct1 .get_local_range (2 )+ 416item_ct1 .get_local_id (2 ); 417i < n ;i += (long long )item_ct1 .get_group_range (2 )* 418item_ct1 .get_local_range (2 )) { 419const int c = (int ) (i /n_embd ),d = (int ) (i %n_embd ); 420// every stream adds the SAME block output; only the weight differs per stream 421out [i ]= R [i ]+ block_out [d ]* w [c ]; 422 } 423} 424 425}// namespace 426 427void gr_set_fp32_activations (bool enabled ) {fp32_activations = enabled ; } 428void gr_set_native_mmvf (bool enabled ) {native_mmvf = enabled ; } 429 430size_t gr_workspace_init (const GrShapes & s ,void * base ,GrWorkspace & out ) { 431const size_t hc_dim = (size_t )s .hc * (size_t )s .n_embd ; 432// ONE table, indexed by the same `k` that assigns the pointers below. The first version of this function 433// sized three locals named `xn`, `xq`, `lq` in a DIFFERENT order from the pointer assignments - `xq` got 434// hc_lr*2 while `lq` got hc_dim*4 - so for the real geometry xq was given 640 bytes where it needed 435// 20,480 and every region overlapped its neighbour. 436// 437// What that looked like is worth recording: `inject` came out ~20% wrong, and rewriting its reduction 438// from block-wide to warp-wide produced BYTE-IDENTICAL wrong answers. Two different reductions agreeing 439// exactly is not a coincidence to investigate - it means the reduction is not where the bug is, and the 440// inputs are. Chasing the reduction instead cost most of a round. 441const size_t sz [5 ]= { 442hc_dim * sizeof (float ),// 0: xn 443hc_dim * sizeof (uint16_t ),// 1: xq 444 (size_t )s .hc_lr * sizeof (uint16_t ),// 2: lq 445hc_dim * sizeof (float ),// 3: gated 446 (size_t )s .hc_lr * sizeof (float ),// 4: lo (FP32 activation experiment) 447 }; 448size_t al [5 ],bytes = 0 ; 449for (int k = 0 ;k < 5 ;++ k ) { 450al [k ]= (sz [k ]+ 15 )& ~(size_t )15 ; 451bytes += al [k ]; 452 } 453out .bytes = bytes ; 454if (base != nullptr ) { 455unsigned char * p = (unsigned char * )base ; 456void * ptr [5 ]; 457for (int k = 0 ;k < 5 ;++ k ) { 458ptr [k ]= p ; 459p += al [k ]; 460 } 461out .xn = (float * )ptr [0 ]; 462out .xq = (uint16_t * )ptr [1 ]; 463out .lq = (uint16_t * )ptr [2 ]; 464out .gated = (float * )ptr [3 ]; 465out .lo = (float * )ptr [4 ]; 466 } 467return bytes ; 468} 469 470void gr_read (const float * R ,const float * w_norm ,const uint16_t * w_down , 471const uint16_t * w_up ,const uint16_t * w_inject ,float eps , 472const GrShapes & s ,const GrWorkspace & ws ,float * mixed , 473float * inject ,void * stream )try { 474if (s .n_embd <=0 || s .hc <=0 || s .hc_lr <=0 )return ; 475if (ws .xn == nullptr || ws .xq == nullptr || ws .lq == nullptr || ws .gated == nullptr || ws .lo == nullptr ) { 476 std::fprintf (stderr ,"gr_read: GrWorkspace is not initialised (see gr_workspace_init)\n" ); 477 std::exit (1 ); 478 } 479if (ws .bytes < gr_workspace_bytes (s )) { 480 std::fprintf (stderr ,"gr_read: GrWorkspace is %zu bytes but this geometry needs %zu\n" , 481ws .bytes ,gr_workspace_bytes (s )); 482 std::exit (1 ); 483 } 484const int n_embd = (int )s .n_embd ,hc = (int )s .hc ,hc_lr = (int )s .hc_lr ; 485const int hc_dim = (int ) (s .hc * s .n_embd ); 486 dpct::queue_ptr st = strata::q_of (stream ); 487 488// One setting selects every projection in this call. Captured graphs retain these kernel variants. 489const bool use_native = native_mmvf ; 490const bool use_fp32 = fp32_activations || use_native ; 491if (use_native ) { 492if ((hc_dim & 1 )!= 0 || (hc_lr & 1 )!= 0 ) 493throw std::invalid_argument ("gr_read native MMVF requires even hc*n_embd and hc_lr" ); 494native_gr_rms_norm_weighted (R ,w_norm ,ws .xn ,n_embd ,hc ,eps ,stream ); 495bf16_gemv_fp32_mmvf (ws .xn ,w_down ,ws .lo ,hc_dim ,hc_lr ,stream ); 496native_gr_down_silu (ws .lo ,hc_lr ,hc ,stream ); 497bf16_gemv_fp32_mmvf (ws .lo ,w_up ,ws .gated ,hc_lr ,hc_dim ,stream ); 498// The existing null-injection contract identifies the final mixer. 499// Pinned qwen4exp uses fused HC pre for layers and the unfused graph for il=-1. 500native_gr_pre_gated (ws .xn ,ws .gated ,mixed ,n_embd ,hc ,w_inject != nullptr ,stream ); 501 }else if (use_fp32 ) { 502 { 503auto exp_props = sycl::ext::oneapi::experimental::properties { 504 sycl::ext::oneapi::experimental::use_root_sync }; 505 dpct::has_capability_or_fail (st -> get_device (), 506 {sycl::aspect::fp64 }); 507 508 strata::kprof::kp (st ,__FILE__ ,__func__ ,__LINE__ )-> template parallel_for < dpct_kernel_name < class gr_norm_kernel_588e81 , 509dpct_kernel_scalar < true>>> ( 510 sycl::nd_range < 3 > (sycl::range (1 ,1 ,hc )* 511 sycl::range (1 ,1 ,THREADS ), 512 sycl::range (1 ,1 ,THREADS )), 513exp_props , 514 [= ](sycl::nd_item < 3 > item_ct1 ) 515 [[sycl ::reqd_sub_group_size (32 )]] { 516gr_norm_kernel < true> (R ,w_norm ,eps ,n_embd ,ws .xn , 517ws .xq ); 518 }); 519 } 520 { 521auto exp_props = sycl::ext::oneapi::experimental::properties { 522 sycl::ext::oneapi::experimental::use_root_sync }; 523 524 strata::kprof::kp (st ,__FILE__ ,__func__ ,__LINE__ )-> template parallel_for < 525dpct_kernel_name < class gr_down_kernel_6ff92b ,float >> ( 526 sycl::nd_range < 3 > (sycl::range (1 ,1 ,hc_lr )* 527 sycl::range (1 ,1 ,THREADS ), 528 sycl::range (1 ,1 ,THREADS )), 529exp_props , 530 [= ](sycl::nd_item < 3 > item_ct1 ) 531 [[sycl ::reqd_sub_group_size (32 )]] { 532gr_down_kernel < float > (ws .xn ,w_down ,hc_dim ,hc_lr ,hc , 533ws .lo ); 534 }); 535 } 536 { 537auto exp_props = sycl::ext::oneapi::experimental::properties { 538 sycl::ext::oneapi::experimental::use_root_sync }; 539 540 strata::kprof::kp (st ,__FILE__ ,__func__ ,__LINE__ )-> template parallel_for < 541dpct_kernel_name < class gr_gate_kernel_abf73c ,float >> ( 542 sycl::nd_range < 3 > ( 543 sycl::range (1 ,1 , (hc_dim + WARPS - 1 ) /WARPS )* 544 sycl::range (1 ,1 ,THREADS ), 545 sycl::range (1 ,1 ,THREADS )), 546exp_props , 547 [= ](sycl::nd_item < 3 > item_ct1 ) 548 [[sycl ::reqd_sub_group_size (32 )]] { 549gr_gate_kernel < float > (ws .lo ,w_up ,ws .xn ,hc_dim ,hc_lr , 550ws .gated ); 551 }); 552 } 553 }else { 554 { 555auto exp_props = sycl::ext::oneapi::experimental::properties { 556 sycl::ext::oneapi::experimental::use_root_sync }; 557 dpct::has_capability_or_fail (st -> get_device (), 558 {sycl::aspect::fp64 }); 559 560 strata::kprof::kp (st ,__FILE__ ,__func__ ,__LINE__ )-> template parallel_for < dpct_kernel_name < class gr_norm_kernel_70bea5 , 561dpct_kernel_scalar < false>>> ( 562 sycl::nd_range < 3 > (sycl::range (1 ,1 ,hc )* 563 sycl::range (1 ,1 ,THREADS ), 564 sycl::range (1 ,1 ,THREADS )), 565exp_props , 566 [= ](sycl::nd_item < 3 > item_ct1 ) 567 [[sycl ::reqd_sub_group_size (32 )]] { 568gr_norm_kernel < false> (R ,w_norm ,eps ,n_embd ,ws .xn , 569ws .xq ); 570 }); 571 } 572 { 573auto exp_props = sycl::ext::oneapi::experimental::properties { 574 sycl::ext::oneapi::experimental::use_root_sync }; 575 576 strata::kprof::kp (st ,__FILE__ ,__func__ ,__LINE__ )-> template parallel_for < 577dpct_kernel_name < class gr_down_kernel_518fbb ,uint16_t >> ( 578 sycl::nd_range < 3 > (sycl::range (1 ,1 ,hc_lr )* 579 sycl::range (1 ,1 ,THREADS ), 580 sycl::range (1 ,1 ,THREADS )), 581exp_props , 582 [= ](sycl::nd_item < 3 > item_ct1 ) 583 [[sycl ::reqd_sub_group_size (32 )]] { 584gr_down_kernel < uint16_t > (ws .xq ,w_down ,hc_dim ,hc_lr , 585hc ,ws .lq ); 586 }); 587 } 588 { 589auto exp_props = sycl::ext::oneapi::experimental::properties { 590 sycl::ext::oneapi::experimental::use_root_sync }; 591 592 strata::kprof::kp (st ,__FILE__ ,__func__ ,__LINE__ )-> template parallel_for < 593dpct_kernel_name < class gr_gate_kernel_feafeb ,uint16_t >> ( 594 sycl::nd_range < 3 > ( 595 sycl::range (1 ,1 , (hc_dim + WARPS - 1 ) /WARPS )* 596 sycl::range (1 ,1 ,THREADS ), 597 sycl::range (1 ,1 ,THREADS )), 598exp_props , 599 [= ](sycl::nd_item < 3 > item_ct1 ) 600 [[sycl ::reqd_sub_group_size (32 )]] { 601gr_gate_kernel < uint16_t > (ws .lq ,w_up ,ws .xn ,hc_dim , 602hc_lr ,ws .gated ); 603 }); 604 } 605 } 606if (!use_native ) 607 { 608auto exp_props = sycl::ext::oneapi::experimental::properties { 609 sycl::ext::oneapi::experimental::use_root_sync }; 610 611 strata::kprof::kp (st ,__FILE__ ,__func__ ,__LINE__ )-> template parallel_for < dpct_kernel_name < class gr_mean_kernel_f4c4e8 >> ( 612 sycl::nd_range < 3 > ( 613 sycl::range (1 ,1 , (n_embd + THREADS - 1 ) /THREADS )* 614 sycl::range (1 ,1 ,THREADS ), 615 sycl::range (1 ,1 ,THREADS )), 616exp_props , [= ](sycl::nd_item < 3 > item_ct1 ) { 617gr_mean_kernel (ws .gated ,n_embd ,hc ,mixed ); 618 }); 619 } 620// Absent for the final mixer, and then nothing is written - computing an injection nobody reads would be 621// a claim, not a convenience. 622if (w_inject != nullptr ) { 623const int nthreads = 32 * hc ; 624if (use_native ) 625bf16_gemv_fp32_mmvf (ws .xn ,w_inject ,inject ,hc_dim ,hc ,stream ); 626else if (use_fp32 ) 627/* 628DPCT1049: The work-group size passed to the SYCL kernel may 629exceed the limit. To get the device limit, query 630info::device::max_work_group_size. Adjust the work-group size if 631needed. 632*/ 633 { 634auto exp_props = sycl::ext::oneapi::experimental::properties { 635 sycl::ext::oneapi::experimental::use_root_sync }; 636 637 strata::kprof::kp (st ,__FILE__ ,__func__ ,__LINE__ )-> template parallel_for < 638dpct_kernel_name < class gr_inject_kernel_569ce0 ,float >> ( 639 sycl::nd_range < 3 > (sycl::range (1 ,1 ,nthreads ), 640 sycl::range (1 ,1 ,nthreads )), 641exp_props , 642 [= ](sycl::nd_item < 3 > item_ct1 ) 643 [[sycl ::reqd_sub_group_size (32 )]] { 644gr_inject_kernel < float > (ws .xn ,w_inject ,hc_dim ,hc , 645inject ); 646 }); 647 }else 648/* 649DPCT1049: The work-group size passed to the SYCL kernel may 650exceed the limit. To get the device limit, query 651info::device::max_work_group_size. Adjust the work-group size if 652needed. 653*/ 654 { 655auto exp_props = sycl::ext::oneapi::experimental::properties { 656 sycl::ext::oneapi::experimental::use_root_sync }; 657 658 strata::kprof::kp (st ,__FILE__ ,__func__ ,__LINE__ )-> template parallel_for < 659dpct_kernel_name < class gr_inject_kernel_d9aa02 ,uint16_t >> ( 660 sycl::nd_range < 3 > (sycl::range (1 ,1 ,nthreads ), 661 sycl::range (1 ,1 ,nthreads )), 662exp_props , 663 [= ](sycl::nd_item < 3 > item_ct1 ) 664 [[sycl ::reqd_sub_group_size (32 )]] { 665gr_inject_kernel < uint16_t > (ws .xq ,w_inject ,hc_dim ,hc , 666inject ); 667 }); 668 } 669 } 670 671/* 672DPCT1010: SYCL uses exceptions to report errors and does not use the 673error codes. The cudaGetLastError function call was replaced with 0. You 674need to rewrite this code. 675*/ 676const dpct::err0 e = 0 ; 677 678if (stream == nullptr ) { 679const dpct::err0 se = DPCT_CHECK_ERROR ( 680 dpct::get_current_device ().queues_wait_and_throw ()); 681 } 682} 683catch (sycl::exception const & exc ) { 684 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 685 <<", line:" <<__LINE__ << std::endl ; 686 std::exit (1 ); 687} 688 689static bool no_multi_gr () { 690static const bool off = [] { 691const char * v = std::getenv ("STRATA_NO_MULTI_GR" ); 692return v != nullptr && v [0 ]!= '\0' && v [0 ]!= '0' ; 693 }(); 694return off ; 695} 696 697void gr_read_multi (const float * R ,const float * w_norm ,const uint16_t * w_down , 698const uint16_t * w_up ,const uint16_t * w_inject ,float eps , 699const GrShapes & s ,const GrWorkspace & ws ,float * xn_multi , 700float * lo_multi ,float * gated_multi ,float * mixed , 701float * inject ,int n_tok ,void * stream )try { 702if (n_tok <=0 || s .n_embd <=0 || s .hc <=0 || s .hc_lr <=0 )return ; 703if (!no_multi_gr ()&& native_mmvf && n_tok > 1 && xn_multi != nullptr && lo_multi != nullptr && gated_multi != nullptr ) { 704const int n_embd = (int )s .n_embd ,hc = (int )s .hc ,hc_lr = (int )s .hc_lr ; 705const int hc_dim = (int ) (s .hc * s .n_embd ); 706if ((hc_dim & 1 )!= 0 || (hc_lr & 1 )!= 0 ) 707throw std::invalid_argument ("gr_read native MMVF requires even hc*n_embd and hc_lr" ); 708native_gr_rms_norm_weighted_multi (R ,w_norm ,xn_multi ,n_embd ,hc ,n_tok ,eps ,stream ); 709bf16_gemv_fp32_mmvf_multi (xn_multi ,hc_dim ,w_down ,lo_multi ,hc_lr ,hc_dim ,hc_lr ,n_tok ,stream ); 710native_gr_down_silu (lo_multi ,hc_lr * n_tok ,hc ,stream ); 711bf16_gemv_fp32_mmvf_multi (lo_multi ,hc_lr ,w_up ,gated_multi ,hc_dim ,hc_lr ,hc_dim ,n_tok ,stream ); 712native_gr_pre_gated_multi (xn_multi ,gated_multi ,mixed ,n_embd ,hc ,n_tok ,w_inject != nullptr ,stream ); 713if (w_inject != nullptr ) 714bf16_gemv_fp32_mmvf_multi (xn_multi ,hc_dim ,w_inject ,inject ,hc ,hc_dim ,hc ,n_tok ,stream ); 715/* 716DPCT1010: SYCL uses exceptions to report errors and does not use 717the error codes. The cudaGetLastError function call was replaced with 0. 718You need to rewrite this code. 719*/ 720const dpct::err0 e = 0 ; 721 722if (stream == nullptr ) { 723const dpct::err0 se = DPCT_CHECK_ERROR ( 724 dpct::get_current_device ().queues_wait_and_throw ()); 725 } 726return ; 727 } 728const size_t hc_dim = (size_t )s .hc * (size_t )s .n_embd ; 729for (int t = 0 ;t < n_tok ;++ t ) { 730gr_read (R + (size_t )t * hc_dim ,w_norm ,w_down ,w_up ,w_inject ,eps ,s ,ws , 731mixed + (size_t )t * s .n_embd ,inject ?inject + (size_t )t * s .hc :nullptr ,stream ); 732 } 733} 734catch (sycl::exception const & exc ) { 735 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 736 <<", line:" <<__LINE__ << std::endl ; 737 std::exit (1 ); 738} 739 740void gr_write (const float * R ,const float * block_out ,const float * inject , 741const GrShapes & s ,float * R_out ,void * stream )try { 742if (s .n_embd <=0 || s .hc <=0 )return ; 743const long long n = (long long )s .hc * s .n_embd ; 744const int blocks = (int ) ((n + THREADS - 1 ) /THREADS ); 745if (native_mmvf ) 746native_gr_post (R ,block_out ,inject ,R_out , (int )s .n_embd , (int )s .hc ,stream ); 747else { 748auto exp_props = sycl::ext::oneapi::experimental::properties { 749 sycl::ext::oneapi::experimental::use_root_sync }; 750 751 strata::kprof::kp (strata::q_of (stream ),__FILE__ ,__func__ ,__LINE__ ) 752-> submit ([& ](sycl::handler & cgh ) { 753/* 754DPCT1083: The size of local memory in the migrated code may 755be different from the original code. Check that the allocated 756memory size in the migrated code is correct. 757*/ 758 sycl::local_accessor < uint8_t ,1 > dpct_local_acc_ct1 ( 759 sycl::range ((size_t )s .hc * sizeof (float )),cgh ); 760 761cgh .parallel_for < 762dpct_kernel_name < class gr_write_kernel_bd7975 >> ( 763 sycl::nd_range < 3 > (sycl::range (1 ,1 ,blocks )* 764 sycl::range (1 ,1 ,THREADS ), 765 sycl::range (1 ,1 ,THREADS )), 766exp_props , [= ](sycl::nd_item < 3 > item_ct1 ) { 767gr_write_kernel ( 768R ,block_out ,inject , (int )s .n_embd , (int )s .hc , 769R_out , 770dpct_local_acc_ct1 771 .get_multi_ptr < sycl::access::decorated::no > () 772 .get ()); 773 }); 774 }); 775 } 776if (stream == nullptr ) { 777const dpct::err0 e = DPCT_CHECK_ERROR ( 778 dpct::get_current_device ().queues_wait_and_throw ()); 779 } 780} 781catch (sycl::exception const & exc ) { 782 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 783 <<", line:" <<__LINE__ << std::endl ; 784 std::exit (1 ); 785} 786 787void gr_write_multi (const float * R ,const float * block_out ,const float * inject , 788const GrShapes & s ,float * R_out ,int n_tok , 789void * stream )try { 790if (n_tok <=0 || s .n_embd <=0 || s .hc <=0 )return ; 791if (!no_multi_gr ()&& native_mmvf && n_tok > 1 ) { 792native_gr_post_multi (R ,block_out ,inject ,R_out , (int )s .n_embd , (int )s .hc ,n_tok ,stream ); 793if (stream == nullptr ) { 794const dpct::err0 e = DPCT_CHECK_ERROR ( 795 dpct::get_current_device ().queues_wait_and_throw ()); 796 } 797return ; 798 } 799const size_t hc_dim = (size_t )s .hc * (size_t )s .n_embd ; 800for (int t = 0 ;t < n_tok ;++ t ) { 801gr_write (R + (size_t )t * hc_dim ,block_out + (size_t )t * s .n_embd ,inject + (size_t )t * s .hc ,s , 802R_out + (size_t )t * hc_dim ,stream ); 803 } 804} 805catch (sycl::exception const & exc ) { 806 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 807 <<", line:" <<__LINE__ << std::endl ; 808 std::exit (1 ); 809} 810 811}// namespace strata::kernels