okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
86bed1c92
main
1// src/kernels/cuda/qsa.cu - P2.S2: the QSA cache, indexer and attention (see include/strata/kernels/qsa.hpp). 2// 3// The header documents the layouts and the scope; this file documents the four decisions that are about the 4// KERNEL rather than about the interface. 5// 6// 1. THE THRESHOLD SEARCH IN `topk_512` RATHER THAN A SORT. The selection has to reproduce `ggml_top_k` on the 7// masked per-cell scores with the reference's tie rule (ascending index), and it has to be EXACT: a 8// different selected set is a different attention input, and `docs/capture-format.md` L127 gives 9// `indexer_ids` no tolerance. The kernel therefore computes the width-th largest score as a 32-bit 10// "order key" by binary lifting (32 monotone passes with `count(key >= cand) >= width`), and then emits - 11// in ONE ascending walk - every cell strictly above it and the first `width - c_gt` cells equal to it. That 12// is provably the same set as sorting by (score desc, index asc) and taking the first width, it needs no 13// scratch and no sort, it is deterministic, and it is the reason `kTopkMaxCells` exists: the whole selection 14// runs in ONE block so the ascending walk is a chunked scan rather than a second global pass. Phase 3 15// replaces it with a radix select; this one is the thing that radix select has to agree with. 16// 17// 2. ONE BLOCK PER HEAD IN `qsa_attend`, SCORES IN SHARED MEMORY. n_ids reaches 2051, so a per-head score 18// vector is 8 KB and 24 heads are 24 blocks: the whole attention is 24 blocks x 256 threads, which is a 19// small grid, but it is also exactly the shape the source uses (one flash tile per query head) and it keeps 20// the softmax's three passes over the scores in shared memory instead of in global. The score loop has one 21// thread per CELL walking the 256 dims sequentially, which reads 16-byte-vectorisable half2 runs; the value 22// loop has one thread per DIM walking the cells, whose warp-wide reads are contiguous within a cell. Both 23// are coalesced for the layout the gather produces. 24// 25// 3. NO `__float2half`. `f16_from_f32` from f16_bits.hpp, for the reason round 193 recorded: `__float2half` 26// produced 0x2600 for 0x26DB and 0x3C01 for exactly 1.0. The parity test checks that converter against 27// vectors generated by numpy's float16, which is an oracle sharing no code with it. 28// 29// 4. THE POOLING ARITHMETIC IS IN DOUBLE AND ORDER-FIXED. `pooled` and the spare key are compared BIT-EXACT 30// against the reference (the spare key's rotation is at position 0, where the f32 rope kernel is an exact 31// identity, so the comparison is not weakened by the rope). That needs the same summation order on both 32// sides: the `r` raw keys are added in CELL order, the sum of squares runs d = 0..idx_dim-1 sequentially, 33// and `__dadd_rn`/`__dmul_rn` block FMA contraction, which would otherwise fuse `ss + m*m` into one 34// operation with no intermediate rounding and land one ulp away from the host. 35// 36// THE `d` IN THOSE NAMES IS NOT COSMETIC. The first version wrote `__fadd_rn`/`__fmul_rn`, which are 37// the SINGLE-precision intrinsics: the compiler converted each double operand to float, operated 38// there, and converted back, so the whole pooling arithmetic ran in single precision - `ss` held only 39// float precision (121.82236480712891 on the device against 121.82236342931094 in the reference). 40// Every comparison still passed at any sane tolerance, the spare key landing 0.4 f32 ulp away; only a 41// BIT-EXACT assertion plus a full-precision probe of the intermediate found it. That is the strongest 42// argument in this file for keeping both. 43#define DPCT_PROFILING_ENABLED 44#include <sycl/sycl.hpp> 45#include "strata/kprof.hpp" 46#include <dpct/dpct.hpp> 47#include "strata/sycl_queue.hpp" 48#include "strata/core/emulate.hpp" 49#include "strata/kernels/qsa.hpp" 50 51#include "strata/kernels/f16_bits.hpp" 52#include "strata/kernels/kv_stream.hpp" 53#include "strata/kernels/rope.hpp" 54#include "strata/kernels/mrope.hpp" 55 56#include <cfloat> 57#include <cmath> 58#include <cstdio> 59#include <cstdlib> 60#include <cstring> 61 62namespace strata::kernels { 63namespace { 64 65constexpr int THREADS = 128 ; 66 67void fail (const char * what ) { 68 std::fprintf (stderr ,"qsa: %s\n" ,what ); 69 std::exit (1 ); 70} 71 72void check_launch (const char * what ) { 73/* 74DPCT1010: SYCL uses exceptions to report errors and does not use the 75error codes. The cudaGetLastError function call was replaced with 0. You 76need to rewrite this code. 77*/ 78const dpct::err0 e = 0 ; 79} 80 81/// The SYNCHRONOUS entry points must check their own wait. Without this the sticky error from a kernel that 82/// faulted becomes visible only at the NEXT call's `cudaGetLastError()`, which then names the wrong kernel - 83/// exactly the mis-attribution that made round 198's first `kv_append` failure look like a later one. 84void check_sync (const char * what )try { 85const dpct::err0 e = 86DPCT_CHECK_ERROR (dpct::get_current_device ().queues_wait_and_throw ()); 87} 88catch (sycl::exception const & exc ) { 89 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 90 <<", line:" <<__LINE__ << std::endl ; 91 std::exit (1 ); 92} 93 94/// Geometry validation. A silently wrong `head_dim % 4` would corrupt the gather's uint2 copy and a silently 95/// wrong `n_head % n_head_kv` would produce a plausible attention with the wrong key, so both are refused. 96void validate (const QsaShapes & s ,const char * who ) { 97if (s .n_head <=0 || s .n_head_kv <=0 || s .head_dim <=0 || s .idx_dim <=0 || s .idx_n_head <=0 || 98s .idx_block < 2 || s .page_size < 1 ) { 99 std::fprintf (stderr ,"qsa: %s: geometry is not set up\n" ,who ); 100 std::exit (1 ); 101 } 102if (s .n_head %s .n_head_kv != 0 ) { 103 std::fprintf (stderr ,"qsa: %s: n_head %lld is not a multiple of n_head_kv %lld\n" ,who , 104 (long long )s .n_head , (long long )s .n_head_kv ); 105 std::exit (1 ); 106 } 107if (s .head_dim %4 != 0 ) { 108 std::fprintf (stderr ,"qsa: %s: head_dim %lld must be a multiple of 4 (the gather copies uint2)\n" ,who , 109 (long long )s .head_dim ); 110 std::exit (1 ); 111 } 112if (s .n_rot <=0 || s .n_rot %2 != 0 || s .n_rot > s .head_dim || s .n_rot > s .idx_dim ) { 113 std::fprintf (stderr ,"qsa: %s: n_rot %lld must be even and <= head_dim %lld and idx_dim %lld\n" ,who , 114 (long long )s .n_rot , (long long )s .head_dim , (long long )s .idx_dim ); 115 std::exit (1 ); 116 } 117if (s .idx_n_head > 32 ) { 118 std::fprintf (stderr ,"qsa: %s: idx_n_head %lld > 32 (one warp per indexer head)\n" ,who , 119 (long long )s .idx_n_head ); 120 std::exit (1 ); 121 } 122} 123 124__dpct_inline__ float h2f (uint16_t bits ) {return f32_from_f16 (bits ); } 125 126// ================= 1. kv_append ================= 127 128__dpct_inline__ void 129kv_append_kernel (uint16_t * __restrict__k_pool ,uint16_t * __restrict__v_pool , 130const int32_t * __restrict__table , 131const int32_t * __restrict__step , 132const float * __restrict__kcur ,const float * __restrict__vcur , 133int kv_heads ,int head_dim ,int page_size ,KvHostPools host ) { 134/* 135DPCT1098: The '*' expression is used instead of the __ldg call. These 136two expressions do not provide the exact same functionality. Check the 137generated code for potential precision and/or performance issues. 138*/ 139auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item < 3 > (); 140const long long pos = (long long )* (step + kStepPos ); 141const int i = item_ct1 .get_group (2 )* item_ct1 .get_local_range (2 )+ 142item_ct1 .get_local_id (2 ); 143if (i >=kv_heads * head_dim )return ; 144const int h = i /head_dim ,d = i - h * head_dim ; 145// `[page][kv_head][page_size][head_dim]`: one head's consecutive cells are contiguous inside a page. 146// KV streaming: the host copy (identity layout) always, the VRAM page only if the block is resident. 147const long long page = (long long )table [pos /page_size ]; 148if (page >=0 ) { 149const long long row = (page * kv_heads + h )* page_size + (pos %page_size ); 150k_pool [row * head_dim + d ]= f16_from_f32 (kcur [i ]); 151v_pool [row * head_dim + d ]= f16_from_f32 (vcur [i ]); 152 } 153if (host .k_pool != nullptr ) { 154const long long row = ((pos /page_size )* kv_heads + h )* page_size + (pos %page_size ); 155host .k_pool [row * head_dim + d ]= f16_from_f32 (kcur [i ]); 156host .v_pool [row * head_dim + d ]= f16_from_f32 (vcur [i ]); 157 } 158} 159 160// ================= 2. indexer_key_append ================= 161 162/// Appends the raw key, and on a block completion pools AND ROTATES the pooled row. One thread per indexer 163/// dim, shared `mean` in double. 164/// 165/// **THE ROTATION IS INSIDE THIS KERNEL, AND THAT IS WHAT MAKES THE WHOLE FUNCTION CAPTURABLE.** It used to be 166/// a second launch from the host wrapper, guarded by `if (pos % idx_block == idx_block - 1)` - a HOST branch on 167/// `pos`, which forced `pos` to be a host scalar, which meant a captured graph would replay the first token's 168/// position forever. Doing it here reads the position from `pos_dev` like every other kernel, so the grid and 169/// the arguments are the same for every token and the graph replays correctly. 170__dpct_inline__ void indexer_key_append_kernel ( 171const float * __restrict__raw ,const int32_t * __restrict__pos_dev , 172int pos_base ,const float * __restrict__w_k_norm ,float eps , 173float * __restrict__tail ,float * __restrict__dead , 174float * __restrict__pooled ,int32_t * __restrict__block_pos ,int idx_dim , 175int r ,int n_rot ,const float * __restrict__cos_tab , 176const float * __restrict__sin_tab ,const int32_t * __restrict__mtab , 177uint8_t * dpct_local ) { 178auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item < 3 > (); 179auto s_mean = (double * )dpct_local ;// idx_dim doubles 180const int d = item_ct1 .get_local_id (2 ); 181/* 182DPCT1098: The '*' expression is used instead of the __ldg call. These 183two expressions do not provide the exact same functionality. Check the 184generated code for potential precision and/or performance issues. 185*/ 186const int pos = (int )* pos_dev ; 187const int slot = pos %r ; 188 189// The RAW tail: a cell that COMPLETES a block is not stored, because the pool below consumes it directly. 190// That is what makes `idx_block - 1` rows enough. 191if (slot < r - 1 )tail [(size_t )slot * idx_dim + d ]= raw [d ]; 192 193// The spare slot's key is `rms_norm(raw[0])`, which is CONSTANT for the sequence and is the only reason 194// cell 0's raw key has to be kept: the three-row tail no longer holds it after the first block. 195if (pos == 0 ) { 196double p = (double )raw [d ]; 197double ss = 0.0 ; 198// Same order as the pooled path, so the two are comparable: sum of squares over the dims, sequential. 199// Every thread computes the same `ss` and uses only its own output element. 200// 201// `__dadd_rn`/`__dmul_rn`, NOT `__fadd_rn`/`__fmul_rn`: the `f` names are the SINGLE-precision 202// intrinsics, and using them on doubles silently rounds every operation to float. `ss` then carries 203// only float precision (121.82236480712891 against the reference's 121.82236342931094) and the spare 204// key comes out 0.4 f32 ulp away - close enough that only a BIT-EXACT assertion notices. `__ddiv_rn` 205// and `__dsqrt_rn` pin the reciprocal square root for the same reason. 206for (int i = 0 ;i < idx_dim ;++ i ) { 207const double v = (double )raw [i ]; 208/* 209DPCT1013: The rounding mode could not be specified and the 210generated code may have different accuracy than the original code. 211Verify the correctness. SYCL math built-in function rounding mode is 212aligned with OpenCL C 1.2 standard. 213*/ 214ss = ss + v * v ; 215 } 216/* 217DPCT1013: The rounding mode could not be specified and the generated 218code may have different accuracy than the original code. Verify the 219correctness. SYCL math built-in function rounding mode is aligned with 220OpenCL C 1.2 standard. 221*/ 222const double inv = 1.0 / sycl::sqrt (ss / (double )idx_dim + (double )eps ); 223float y = (float ) (p * inv * (double )w_k_norm [d ]); 224// The spare rotates at position 0 - ALWAYS row 0 of the table, whatever `pos_base` is, as the native 225// indexer's spare does. At angle 0 the sine is exactly 0 in every scaling (sin(0) * mscale), so the 226// pair rotation reduces to `v * cos_tab[pair]` with no partner element to read (and no barrier). 227// Unscaled, row 0 is exactly (1, 0) and `v * 1.0f` is `v` bit for bit - today's value, which the 228// parity test holds bit-exact. Under YaRN row 0 is (mscale, 0): the rotated dims carry the magnitude 229// correction exactly like every other pooled row and like the native kernel's spare (the unrotated 230// dims pass through, as in the rotation of the completed blocks below). Skipping the rotation here, 231// as this kernel once did, left `dead` and `pooled[0]` the only unscaled keys of a scaled cache. 232if (d < n_rot )y *=cos_tab [d % (n_rot /2 )]; 233dead [d ]= y ; 234pooled [d ]= y ; 235 } 236 237if (slot != r - 1 )return ; 238/* 239DPCT1065: Consider replacing sycl::nd_item::barrier() with 240sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better 241performance if there is no access to global memory. 242*/ 243item_ct1 .barrier ();// the tail rows this thread is about to read are 244// written above 245 246// The mean of this block's r raw keys, in CELL order: the r-1 tail rows (slots 0..r-2) then the incoming 247// cell (slot r-1). The sum of r f32 values is exact in double, so the mean's order cannot matter here - 248// but the order of the SUM OF SQUARES below can, and it is fixed to d ascending on both sides. 249double m = 0.0 ; 250/* 251DPCT1013: The rounding mode could not be specified and the generated code 252may have different accuracy than the original code. Verify the correctness. SYCL 253math built-in function rounding mode is aligned with OpenCL C 1.2 standard. 254*/ 255#pragma unroll 256for (int j = 0 ;j < r - 1 ;++ j ) 257m = m + (double )tail [(size_t )j * idx_dim + d ]; 258/* 259DPCT1013: The rounding mode could not be specified and the generated 260code may have different accuracy than the original code. Verify the 261correctness. SYCL math built-in function rounding mode is aligned with 262OpenCL C 1.2 standard. 263*/ 264m = m + (double )raw [d ]; 265m = m / (double )r ; 266s_mean [d ]= m ; 267/* 268DPCT1065: Consider replacing sycl::nd_item::barrier() with 269sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better 270performance if there is no access to global memory. 271*/ 272item_ct1 .barrier (); 273 274double ss = 0.0 ; 275/* 276DPCT1013: The rounding mode could not be specified and the generated code 277may have different accuracy than the original code. Verify the correctness. SYCL 278math built-in function rounding mode is aligned with OpenCL C 1.2 standard. 279*/ 280#pragma unroll 281for (int i = 0 ;i < idx_dim ;++ i )ss = ss + s_mean [i ]* s_mean [i ]; 282/* 283DPCT1013: The rounding mode could not be specified and the generated 284code may have different accuracy than the original code. Verify the 285correctness. SYCL math built-in function rounding mode is aligned with 286OpenCL C 1.2 standard. 287*/ 288const double inv = 1.0 / sycl::sqrt (ss / (double )idx_dim + (double )eps ); 289 290const int b = pos /r ; 291pooled [(size_t )b * idx_dim + d ]= (float ) (m * inv * (double )w_k_norm [d ]); 292// The spare slot MOVES to b+1 and is rewritten with the same constant value. 293pooled [(size_t ) (b + 1 )* idx_dim + d ]= dead [d ]; 294// The rotation position for this row, kept because a capture reader and the debug dumps want it. It is the 295// block's first cell's POSITION, `pos_base + b*r`, and NOT the cell index `b*r`. 296if (d == 0 )* block_pos = (int32_t ) (pos_base + b * r ); 297/* 298DPCT1065: Consider replacing sycl::nd_item::barrier() with 299sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better 300performance if there is no access to global memory. 301*/ 302item_ct1 .barrier ();// the row is complete only now; the rotation below 303// reads TWO elements of it 304 305// ---- the rotation of the row that just completed, IN PLACE. 306// 307// `i` pairs with `i + half`, so only the first `half` threads do any work - but EVERY thread must reach the 308// barrier above, which is why the guard is here and not around the whole block's tail. 309// 310// The position is the BLOCK'S FIRST cell (`ref/qsa.py` PROPERTY 4: rotating at the block's last cell keeps 311// every shape and every magnitude), and it comes from `pos_base`, which is constant for a sequence. 312const int half = n_rot /2 ; 313if (d < half ) { 314float * row = pooled + (size_t )b * idx_dim ; 315const size_t toff = (size_t )mrope_pos (mtab ,pos_base + b * r ,d )* half ; 316// THE SAME `rope_neox_pair` THE STANDALONE ROPE KERNEL USES. A second transcription of the pairing is 317// what this project keeps finding written down wrong. 318rope_neox_pair (row [d ],row [half + d ],cos_tab [toff + d ],sin_tab [toff + d ],row [d ],row [half + d ]); 319 } 320} 321 322// ================= 3. qsa_index ================= 323 324/// One warp per indexer head, one block per pooled row; thread 0 sums the relu'd dots IN HEAD ORDER and maps 325/// the row's score onto its cells. The reference's Relu is PER HEAD, so the dots cannot be summed first. 326__dpct_inline__ void qsa_index_kernel (const float * __restrict__pooled , 327const float * __restrict__q_idx , 328const float * __restrict__bias , 329int idx_n_head ,int idx_dim ,long long r , 330const int32_t * __restrict__step , 331float * __restrict__cell_scores ) { 332/* 333DPCT1098: The '*' expression is used instead of the __ldg call. These 334two expressions do not provide the exact same functionality. Check the 335generated code for potential precision and/or performance issues. 336*/ 337auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item < 3 > (); 338const long long n_bid = (long long )* (step + kStepNBid ); 339/* 340DPCT1098: The '*' expression is used instead of the __ldg call. These 341two expressions do not provide the exact same functionality. Check the 342generated code for potential precision and/or performance issues. 343*/ 344const long long n_kv = (long long )* (step + kStepNKv ); 345auto & s_dot = 346* sycl::ext::oneapi::group_local_memory_for_overwrite < double [32 ]> ( 347 sycl::ext::oneapi::this_work_item::get_work_group < 3 > ()); 348const long long b = item_ct1 .get_group (2 ); 349// A BLOCK PAST THE COMPLETED-BLOCK COUNT MUST DO NOTHING. This is what lets the LAYER launch a CONSTANT 350// grid of the maximum block count instead of this token's `n_bid + 1`: a grid sized from a per-token value 351// is a per-token LAUNCH CONFIGURATION, and a CUDA graph bakes those in exactly as it bakes in an argument. 352// Without this guard, a capacity-sized grid would score pooled rows that have not been written yet - 353// reading zeros and producing a plausible score for a block that does not exist. 354if (b > n_bid )return ; 355const int wid = item_ct1 .get_local_id (2 ) >>5 , 356lane = item_ct1 .get_local_id (2 )& 31 ; 357if (wid == 0 )s_dot [lane ]= 0.0 ;// thread 0 reads all idx_n_head entries; zero the unused ones 358item_ct1 .barrier (sycl::access::fence_space::local_space ); 359 360double acc = 0.0 ; 361#pragma unroll 362for (int d = lane ;d < idx_dim ;d += 32 ) 363/* 364DPCT1013: The rounding mode could not be specified and the generated 365code may have different accuracy than the original code. Verify the 366correctness. SYCL math built-in function rounding mode is aligned with 367OpenCL C 1.2 standard. 368*/ 369acc = acc + (double )pooled [(size_t )b * idx_dim + d ]* 370 (double )q_idx [(size_t )wid * idx_dim + d ]; 371/* 372DPCT1108: '__shfl_xor_sync' was migrated with the experimental feature 373masked sub_group function which may not be supported by all compilers or 374runtimes. You may need to adjust the code. 375*/ 376/* 377DPCT1013: The rounding mode could not be specified and the generated code 378may have different accuracy than the original code. Verify the correctness. SYCL 379math built-in function rounding mode is aligned with OpenCL C 1.2 standard. 380*/ 381#pragma unroll 382for (int o = 16 ;o > 0 ;o >>=1 )acc = 383acc + dpct::experimental::permute_sub_group_by_xor ( 3840xffffffffu , 385 sycl::ext::oneapi::this_work_item::get_sub_group (),acc ,o ); 386if (lane == 0 )s_dot [wid ]= acc ; 387item_ct1 .barrier (sycl::access::fence_space::local_space ); 388 389if (item_ct1 .get_local_id (2 )!= 0 )return ; 390double score = 0.0 ; 391#pragma unroll 392for (int h = 0 ;h < idx_n_head ;++ h )score += 393 (s_dot [h ]> 0.0 ) ?s_dot [h ] :0.0 ; 394if (bias != nullptr )score += (double )bias [b ]; 395// cell_block: cells of block b for b < n_bid, and the WHOLE incomplete tail for b == n_bid 396long long lo = b * r ,hi = lo + r ; 397if (b == n_bid )hi = n_kv ; 398if (hi > n_kv )hi = n_kv ; 399// llama-memory-hybrid-idx.cpp::set_input_qsa gives incomplete-tail cells 400// a finite +1e9 bias before top-k. Read the current step on every replay: 401// the spare row becomes an ordinary block as soon as its fourth cell arrives. 402float sc = (float )score ; 403if (b == n_bid && n_kv %r != 0 )sc += 1e9f ; 404#pragma unroll 405for (long long j = lo ;j < hi ;++ j )cell_scores [j ]= sc ; 406} 407 408// ================= 4. topk_512 ================= 409 410/// Total order over f32 as an unsigned key, so one integer comparison orders scores with numpy's float 411/// semantics. `+ 0.0f` maps -0.0 to +0.0 because numpy treats them as EQUAL (and would break the tie by 412/// index), while the raw bit pattern orders them. A NaN is mapped to 0, below every real key, i.e. never 413/// selected - numpy sorts NaN LAST, and silently selecting one would be worse than the disagreement. 414__dpct_inline__ uint32_t order_key (float s ) { 415const float v = s + 0.0f ; 416if (!(v == v ))return 0u ; 417uint32_t b ; 418memcpy (& b ,& v ,4 ); 419return (b & 0x80000000u ) ? ~b : (b |0x80000000u ); 420} 421 422constexpr int TOPK_THREADS = 256 ; 423 424/* 425DPCT1110: The total declared local variable size in device function 426topk_kernel exceeds 128 bytes and may cause high register pressure. Consult with 427your hardware vendor to find the total register size available and adjust the 428code, or use smaller sub-group size to avoid high register pressure. 429*/ 430__dpct_inline__ void topk_kernel (const float * __restrict__scores , 431const int32_t * __restrict__step , 432int * __restrict__out_ids ) { 433/* 434DPCT1098: The '*' expression is used instead of the __ldg call. These 435two expressions do not provide the exact same functionality. Check the 436generated code for potential precision and/or performance issues. 437*/ 438auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item < 3 > (); 439const long long n_kv = (long long )* (step + kStepNKv ); 440/* 441DPCT1098: The '*' expression is used instead of the __ldg call. These 442two expressions do not provide the exact same functionality. Check the 443generated code for potential precision and/or performance issues. 444*/ 445const long long width = (long long )* (step + kStepWidth ); 446auto & s_a = 447* sycl::ext::oneapi::group_local_memory_for_overwrite < int [TOPK_THREADS ]> ( 448 sycl::ext::oneapi::this_work_item::get_work_group < 3 > ()); 449auto & s_b = 450* sycl::ext::oneapi::group_local_memory_for_overwrite < int [TOPK_THREADS ]> ( 451 sycl::ext::oneapi::this_work_item::get_work_group < 3 > ()); 452auto & s_cgt = 453* sycl::ext::oneapi::group_local_memory_for_overwrite < long long > ( 454 sycl::ext::oneapi::this_work_item::get_work_group < 3 > ()); 455const int t = item_ct1 .get_local_id (2 ); 456const long long chunk = (n_kv + TOPK_THREADS - 1 ) /TOPK_THREADS ; 457const long long lo = (long long )t * chunk ; 458long long hi = lo + chunk ; 459if (hi > n_kv )hi = n_kv ; 460 461// ---- binary lifting: the largest key v with count(key >= v) >= width. Monotone in v, so setting the 462// bits from the top down lands on exactly that value, and count(>= v) >= width > count(>= v+1). 463uint32_t v = 0u ; 464for (int bit = 31 ;bit >=0 ;-- bit ) { 465const uint32_t cand = v | (1u <<bit ); 466int c = 0 ; 467#pragma unroll 468for (long long j = lo ;j < hi ; 469++ j )if (order_key (scores [j ]) >=cand )++ c ; 470s_a [t ]= c ; 471/* 472DPCT1118: SYCL group functions and algorithms must be encountered in 473converged control flow. You may need to adjust the code. 474*/ 475item_ct1 .barrier (sycl::access::fence_space::local_space ); 476#pragma unroll 477for (int s = TOPK_THREADS /2 ;s > 0 ;s >>=1 ) { 478if (t < s )s_a [t ]+= s_a [t + s ]; 479/* 480DPCT1118: SYCL group functions and algorithms must be 481encountered in converged control flow. You may need to adjust the 482code. 483*/ 484item_ct1 .barrier (sycl::access::fence_space::local_space ); 485 } 486const int tot = s_a [0 ]; 487/* 488DPCT1118: SYCL group functions and algorithms must be encountered in 489converged control flow. You may need to adjust the code. 490*/ 491item_ct1 .barrier ( 492 sycl::access::fence_space::local_space );// before the next round 493// overwrites s_a 494if (tot >= (int )width )v = cand ; 495 } 496const uint32_t thr = v ; 497 498// ---- counts and their exclusive prefixes. The prefixes are computed by thread 0 in one walk, which is 499// 256 iterations ONCE per kernel and removes 2 log-steps of scan machinery from a path that is already 500// 32 passes deep. 501int gt = 0 ,eq = 0 ; 502for (long long j = lo ;j < hi ;++ j ) { 503const uint32_t k = order_key (scores [j ]); 504if (k > thr )++ gt ; 505else if (k == thr )++ eq ; 506 } 507s_a [t ]= gt ; 508s_b [t ]= eq ; 509item_ct1 .barrier (sycl::access::fence_space::local_space ); 510if (t == 0 ) { 511long long ag = 0 ,ae = 0 ; 512for (int i = 0 ;i < TOPK_THREADS ;++ i ) { 513const int g = s_a [i ],e = s_b [i ]; 514s_a [i ]= (int )ag ; 515s_b [i ]= (int )ae ; 516ag += g ; 517ae += e ; 518 } 519s_cgt = ag ;// how many are strictly above the threshold, i.e. where the equals start 520 } 521item_ct1 .barrier (sycl::access::fence_space::local_space ); 522// THE RANK VS THE COUNT. `off_eq` is how many equal-to-threshold cells come BEFORE this chunk, and it is 523// compared against `eq_budget`, the number of them the selection has room for. The first version wrote 524// `c_gt + prefix_eq` - where an equal cell would land in a "greater-than first, then equal" LAYOUT - and 525// compared THAT against the budget. With distinct scores `c_gt == width` and `eq_budget == 0`, so nothing 526// was ever selected at the threshold and the kernel emitted `width` ids with one missing and one stale. 527// Every all-equal fixture passed, because there `c_gt == 0` and the two readings coincide. 528const long long off_eq = s_b [t ]; 529const long long eq_budget = width - s_cgt ; 530 531// ---- how many this chunk selects, so the ascending walk can be scattered into place 532int sel = 0 ; 533 { 534long long e = off_eq ; 535for (long long j = lo ;j < hi ;++ j ) { 536const uint32_t k = order_key (scores [j ]); 537if (k > thr )++ sel ; 538else if (k == thr && e < eq_budget ) {++ sel ;++ e ; } 539 } 540 } 541s_a [t ]= sel ; 542item_ct1 .barrier (sycl::access::fence_space::local_space ); 543if (t == 0 ) { 544long long a = 0 ; 545for (int i = 0 ;i < TOPK_THREADS ;++ i ) { 546const int c = s_a [i ]; 547s_a [i ]= (int )a ; 548a += c ; 549 } 550 } 551item_ct1 .barrier (sycl::access::fence_space::local_space ); 552 553// ---- emit, walking the cells ASCENDING so the tie rule's "first by index" is the walk order itself 554long long w = s_a [t ]; 555long long e = off_eq ; 556for (long long j = lo ;j < hi ;++ j ) { 557const uint32_t k = order_key (scores [j ]); 558if (k > thr )out_ids [w ++ ]= (int )j ; 559else if (k == thr && e < eq_budget ) {++ e ;out_ids [w ++ ]= (int )j ; } 560 } 561} 562 563// ================= 5. kv_gather ================= 564 565__dpct_inline__ void kv_gather_kernel ( 566const uint16_t * __restrict__k_pool ,const uint16_t * __restrict__v_pool , 567const int32_t * __restrict__table ,const int32_t * __restrict__ids , 568const int32_t * __restrict__step ,int kv_heads ,int head_dim ,int page_size , 569uint16_t * __restrict__k_scratch ,uint16_t * __restrict__v_scratch ) { 570/* 571DPCT1098: The '*' expression is used instead of the __ldg call. These 572two expressions do not provide the exact same functionality. Check the 573generated code for potential precision and/or performance issues. 574*/ 575auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item < 3 > (); 576const long long n_ids = (long long )* (step + kStepWidth ); 577const int per = head_dim /4 ;// 4 halfs per uint2 578const long long total = n_ids * kv_heads * per ; 579const long long i = 580item_ct1 .get_group (2 )* (long long )item_ct1 .get_local_range (2 )+ 581item_ct1 .get_local_id (2 ); 582if (i >=total )return ; 583const long long id = i / (kv_heads * (long long )per ); 584const int rem = (int ) (i % (kv_heads * (long long )per )); 585const int h = rem /per ,q = rem - h * per ; 586const int cell = ids [id ]; 587const long long page = (long long )table [cell /page_size ]; 588const long long src = ((page * kv_heads + h )* page_size + (cell %page_size ))* (long long )per + q ; 589const long long dst = (id * kv_heads + h )* (long long )per + q ; 590reinterpret_cast < sycl::uint2 *> (k_scratch )[dst ]= 591reinterpret_cast < const sycl::uint2 *> (k_pool )[src ]; 592reinterpret_cast < sycl::uint2 *> (v_scratch )[dst ]= 593reinterpret_cast < const sycl::uint2 *> (v_pool )[src ]; 594} 595 596// ================= 6. qsa_attend ================= 597 598__dpct_inline__ float warp_max (float v ) { 599/* 600DPCT1108: '__shfl_xor_sync' was migrated with the experimental feature 601masked sub_group function which may not be supported by all compilers or 602runtimes. You may need to adjust the code. 603*/ 604#pragma unroll 605for (int o = 16 ;o > 0 ;o >>=1 )v = sycl::fmax ( 606v , dpct::experimental::permute_sub_group_by_xor ( 6070xffffffffu , sycl::ext::oneapi::this_work_item::get_sub_group (), 608v ,o )); 609return v ; 610} 611 612__dpct_inline__ float warp_sum (float v ) { 613/* 614DPCT1108: '__shfl_xor_sync' was migrated with the experimental feature 615masked sub_group function which may not be supported by all compilers or 616runtimes. You may need to adjust the code. 617*/ 618#pragma unroll 619for (int o = 16 ;o > 0 ;o >>=1 )v += 620 dpct::experimental::permute_sub_group_by_xor ( 6210xffffffffu , sycl::ext::oneapi::this_work_item::get_sub_group (),v , 622o ); 623return v ; 624} 625 626/// One block per query head. `s` holds the scores, which are then overwritten with the softmax weights. 627/* 628DPCT1110: The total declared local variable size in device function 629qsa_attend_kernel exceeds 128 bytes and may cause high register pressure. 630Consult with your hardware vendor to find the total register size available and 631adjust the code, or use smaller sub-group size to avoid high register pressure. 632*/ 633__dpct_inline__ void qsa_attend_kernel ( 634const float * __restrict__q ,const uint16_t * __restrict__k_scratch , 635const uint16_t * __restrict__v_scratch ,const int32_t * __restrict__step , 636int n_head ,int n_head_kv ,int head_dim ,float * __restrict__attn , 637float * __restrict__weights ,uint8_t * dpct_local ) { 638/* 639DPCT1098: The '*' expression is used instead of the __ldg call. These 640two expressions do not provide the exact same functionality. Check the 641generated code for potential precision and/or performance issues. 642*/ 643auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item < 3 > (); 644const long long n_ids = (long long )* (step + kStepWidth ); 645auto s_w = (float * )dpct_local ;// CAPACITY floats (scores, then weights) + 646// 32 for the reductions 647float * red = s_w ;// red[0..31] live past the scores/weights: see the launch 648float * w = s_w + 32 ; 649const int h = item_ct1 .get_group (2 ); 650const int d = item_ct1 .get_local_id (2 ); 651// AN EMPTY SELECTION IS HANDLED HERE, not by a host early return. The wrapper used to check `n_ids == 0` 652// and `cudaMemsetAsync` the output, but `n_ids` is a device value now - so the branch has to be on the 653// device, and this is also the only form a graph can replay: the launch is unconditional and the kernel 654// decides. Below the selection bound the selection is the IDENTITY, so `n_ids` is never 0 there; it is 655// reachable only for a genuinely empty cache, and the reference returns zeros for that. 656if (n_ids == 0 ) { 657#pragma unroll 658for (int i = d ;i < head_dim ;i += item_ct1 .get_local_range (2 )) 659attn [(size_t )h * head_dim + i ]= 0.0f ; 660return ; 661 } 662const int kv = h / (n_head /n_head_kv );// ops.cpp L8729: iv2 = iq2 / rv2, NOT h % n_head_kv 663const float scale = 1.0f / sycl::sqrt ((float )head_dim ); 664const int lane = d & 31 ,wid = d >>5 , 665nwarp = (int )((item_ct1 .get_local_range (2 )+ 31 ) >>5 ); 666 667for (long long j = d ;j < n_ids ;j += item_ct1 .get_local_range (2 )) { 668const uint16_t * krow = k_scratch + (j * n_head_kv + kv )* head_dim ; 669float acc = 0.0f ; 670#pragma unroll 671for (int i = 0 ;i < head_dim ;++ i )acc += 672h2f (krow [i ])* q [(size_t )h * head_dim + i ]; 673w [j ]= acc * scale ; 674 } 675/* 676DPCT1065: Consider replacing sycl::nd_item::barrier() with 677sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better 678performance if there is no access to global memory. 679*/ 680item_ct1 .barrier (); 681 682float mx = - FLT_MAX ;// not -inf, whose double -> float conversion nvcc warns about 683#pragma unroll 684for (long long j = d ;j < n_ids ;j += item_ct1 .get_local_range (2 )) 685mx = sycl::fmax (mx ,w [j ]); 686mx = warp_max (mx ); 687if (lane == 0 )red [wid ]= mx ; 688/* 689DPCT1065: Consider replacing sycl::nd_item::barrier() with 690sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better 691performance if there is no access to global memory. 692*/ 693item_ct1 .barrier (); 694if (wid == 0 ) { 695mx = (lane < nwarp ) ?red [lane ] :- FLT_MAX ; 696mx = warp_max (mx ); 697if (lane == 0 )red [0 ]= mx ; 698 } 699/* 700DPCT1065: Consider replacing sycl::nd_item::barrier() with 701sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better 702performance if there is no access to global memory. 703*/ 704item_ct1 .barrier (); 705mx = red [0 ]; 706/* 707DPCT1065: Consider replacing sycl::nd_item::barrier() with 708sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better 709performance if there is no access to global memory. 710*/ 711item_ct1 .barrier (); 712 713float sum = 0.0f ; 714for (long long j = d ;j < n_ids ;j += item_ct1 .get_local_range (2 )) { 715const float e = sycl::native::exp (w [j ]- mx ); 716w [j ]= e ; 717sum += e ; 718 } 719sum = warp_sum (sum ); 720if (lane == 0 )red [wid ]= sum ; 721/* 722DPCT1065: Consider replacing sycl::nd_item::barrier() with 723sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better 724performance if there is no access to global memory. 725*/ 726item_ct1 .barrier (); 727if (wid == 0 ) { 728sum = (lane < nwarp ) ?red [lane ] :0.0f ; 729sum = warp_sum (sum ); 730if (lane == 0 )red [0 ]= 1.0f /sum ; 731 } 732/* 733DPCT1065: Consider replacing sycl::nd_item::barrier() with 734sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better 735performance if there is no access to global memory. 736*/ 737item_ct1 .barrier (); 738const float inv = red [0 ]; 739/* 740DPCT1065: Consider replacing sycl::nd_item::barrier() with 741sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better 742performance if there is no access to global memory. 743*/ 744item_ct1 .barrier (); 745 746float acc = 0.0f ; 747#pragma unroll 748for (long long j = 0 ;j < n_ids ;++ j ) 749acc += (w [j ]* inv )* h2f (v_scratch [(j * n_head_kv + kv )* head_dim + d ]); 750attn [(size_t )h * head_dim + d ]= acc ; 751if (weights != nullptr ) { 752#pragma unroll 753for (long long j = d ;j < n_ids ;j += item_ct1 .get_local_range (2 )) 754weights [(size_t )h * n_ids + j ]= w [j ]* inv ; 755 } 756} 757 758// ================= 7. qsa_gate_apply ================= 759 760__dpct_inline__ void qsa_gate_apply_kernel (const float * __restrict__attn , 761const float * __restrict__q_full , 762int n_head ,int head_dim , 763uint16_t * __restrict__out ) { 764auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item < 3 > (); 765const long long i = 766item_ct1 .get_group (2 )* (long long )item_ct1 .get_local_range (2 )+ 767item_ct1 .get_local_id (2 ); 768if (i >= (long long )n_head * head_dim )return ; 769const int h = (int ) (i /head_dim ),d = (int ) (i %head_dim ); 770const double g = (double )q_full [((size_t )h * 2 * head_dim )+ head_dim + d ];// the SECOND half 771const double sig = 1.0 / (1.0 + sycl::exp (- g )); 772out [i ]= f16_from_f32 ((float ) ((double )attn [i ]* sig )); 773} 774 775inline unsigned grid_for (long long n ,int threads ) { 776return (unsigned ) ((n + threads - 1 ) /threads ); 777} 778 779}// namespace 780 781/// THE STEP STATE, UPLOADED. Every kernel below reads its per-token counts from here rather than from a kernel 782/// argument, because a CUDA graph bakes arguments in at capture time - see the long note in `qsa.hpp`. This 783/// module-level buffer is what lets the OLD host-scalar signatures keep working unchanged while the kernels 784/// already read the device values; the layer will pass its own buffer once it captures. 785/// 786/// It is per-PROCESS and reused, which is safe because the upload and the kernel that reads it are on the same 787/// stream and the host is the only writer. `cudaMemcpyAsync` on the null stream is ordered against the null 788/// stream's kernels, which is what every direct-launch caller here uses. 789namespace { 790 791int32_t * step_scratch ()try { 792static int32_t * d_step = nullptr ; 793if (d_step == nullptr ) { 794if (DPCT_CHECK_ERROR ( 795d_step = (int32_t * )sycl::malloc_device ( 796qsa_step_bytes (), dpct::get_in_order_queue ()))!= 0 ) { 797 std::fprintf (stderr ,"qsa: step upload: cudaMalloc failed\n" ); 798 std::exit (1 ); 799 } 800 } 801return d_step ; 802} 803catch (sycl::exception const & exc ) { 804 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 805 <<", line:" <<__LINE__ << std::endl ; 806 std::exit (1 ); 807} 808 809void step_upload_raw (const int32_t * h_step )try { 810int32_t * d = step_scratch (); 811/* 812DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming in 813the original code the source host memory is pageable memory. If the memory 814is not pageable, call wait() on event return by memcpy API to ensure 815synchronization behavior. 816*/ 817if (DPCT_CHECK_ERROR (dpct::get_in_order_queue ().memcpy ( 818d ,h_step ,qsa_step_bytes ()).wait ())!= 0 ) { 819 std::fprintf (stderr ,"qsa: step upload: cudaMemcpy failed\n" ); 820 std::exit (1 ); 821 } 822} 823catch (sycl::exception const & exc ) { 824 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 825 <<", line:" <<__LINE__ << std::endl ; 826 std::exit (1 ); 827} 828 829/// From a POSITION: fills all four entries. This is the form the layer will use, and the only form that cannot 830/// produce an inconsistent `n_kv`/`n_bid`/`width`. 831const int32_t * step_upload (int64_t pos ,int64_t n_kv_hint ,const QsaShapes & s ) { 832int32_t h [kStepCount ]; 833qsa_step_fill (h ,pos ,s ); 834// A caller that also knows `n_kv` is CHECKED against it rather than believed: a disagreement is exactly the 835// inconsistency `qsa_step_fill` exists to make impossible, so it is worth an exit rather than a silent 836// preference for one of the two. 837if (n_kv_hint >=0 && n_kv_hint != (int64_t )h [kStepNKv ]) { 838 std::fprintf (stderr ,"qsa: step upload: n_kv %lld disagrees with pos+1 = %d\n" , (long long )n_kv_hint , 839h [kStepNKv ]); 840 std::exit (1 ); 841 } 842step_upload_raw (h ); 843return step_scratch (); 844} 845 846/// From a WIDTH. `kv_gather` and `qsa_attend` are handed the selection width directly and never see `pos`, so 847/// only that entry is meaningful for them; the others are set consistently anyway rather than left stale, 848/// because a stale entry is a value the NEXT kernel might read. 849const int32_t * step_upload_width (int64_t width ,const QsaShapes & s ) { 850int32_t h [kStepCount ]; 851for (int i = 0 ;i < kStepCount ;++ i )h [i ]= 0 ; 852h [kStepWidth ]= (int32_t )width ; 853 (void )s ; 854step_upload_raw (h ); 855return step_scratch (); 856} 857 858}// namespace 859 860// ================= THE CAPTURABLE ENTRY POINTS ================= 861// 862// These are the REAL implementations: every launch below is sized from a constant capacity and every per-token 863// count comes from `step`. The host-scalar entry points further down are wrappers that fill a module-level step 864// buffer and forward this token's counts as the capacities. 865 866void kv_append_step (uint16_t * k_pool ,uint16_t * v_pool ,const int32_t * page_table ,const int32_t * step , 867const float * kcur ,const float * vcur ,const QsaShapes & s ,void * stream ,const KvHostPools * host ) { 868validate (s ,"kv_append" ); 869if (step == nullptr )fail ("kv_append: step is null" ); 870// The grid is the head x dim count, which is a CONSTANT - `kv_append` writes one cell. 871const long long n = s .n_head_kv * s .head_dim ; 872 { 873auto exp_props = sycl::ext::oneapi::experimental::properties { 874 sycl::ext::oneapi::experimental::use_root_sync }; 875 876 strata::kprof::kp (strata::q_of (stream ),__FILE__ ,__func__ ,__LINE__ ) 877-> submit ([& ](sycl::handler & cgh ) { 878KvHostPools host_host_KvHostPools_ct9 = 879host ?* host :KvHostPools {}; 880 881cgh .parallel_for < 882dpct_kernel_name < class kv_append_kernel_19f129 >> ( 883 sycl::nd_range < 3 > (sycl::range (1 ,1 ,grid_for (n ,THREADS ))* 884 sycl::range (1 ,1 ,THREADS ), 885 sycl::range (1 ,1 ,THREADS )), 886exp_props , [= ](sycl::nd_item < 3 > item_ct1 ) { 887kv_append_kernel (k_pool ,v_pool ,page_table ,step ,kcur , 888vcur , (int )s .n_head_kv , 889 (int )s .head_dim , (int )s .page_size , 890host_host_KvHostPools_ct9 ); 891 }); 892 }); 893 } 894check_launch ("kv_append" ); 895if (stream == nullptr )check_sync ("kv_append" ); 896} 897 898void qsa_index_step (const float * pooled ,const float * q_idx ,const float * bias ,const QsaShapes & s , 899const int32_t * step ,int64_t max_blocks ,float * cell_scores ,void * stream ) { 900validate (s ,"qsa_index" ); 901if (step == nullptr )fail ("qsa_index: step is null" ); 902if (max_blocks <=0 )fail ("qsa_index: max_blocks must be positive" ); 903// THE GRID IS `max_blocks`, A CONSTANT - not this token's `n_bid + 1`. The kernel returns for 904// `b > n_bid`, so the surplus blocks cost a launch and nothing else. 905const int threads = 32 * (int )s .idx_n_head ; 906/* 907DPCT1049: The work-group size passed to the SYCL kernel may exceed the 908limit. To get the device limit, query info::device::max_work_group_size. 909Adjust the work-group size if needed. 910*/ 911 { 912auto exp_props = sycl::ext::oneapi::experimental::properties { 913 sycl::ext::oneapi::experimental::use_root_sync }; 914 dpct::has_capability_or_fail ( 915 strata::q_of (stream )-> get_device (), 916 {sycl::aspect::fp64 }); 917 918 strata::kprof::kp (strata::q_of (stream ),__FILE__ ,__func__ ,__LINE__ ) 919-> template parallel_for < dpct_kernel_name < class qsa_index_kernel_bb65cd >> ( 920 sycl::nd_range < 3 > (sycl::range (1 ,1 , (unsigned )max_blocks )* 921 sycl::range (1 ,1 ,threads ), 922 sycl::range (1 ,1 ,threads )), 923exp_props , 924 [= ](sycl::nd_item < 3 > item_ct1 ) 925 [[sycl ::reqd_sub_group_size (32 )]] { 926qsa_index_kernel (pooled ,q_idx ,bias , (int )s .idx_n_head , 927 (int )s .idx_dim ,s .idx_block ,step , 928cell_scores ); 929 }); 930 } 931check_launch ("qsa_index" ); 932if (stream == nullptr )check_sync ("qsa_index" ); 933} 934 935void topk_512_step (const float * cell_scores ,const QsaShapes & s ,int64_t cap ,const int32_t * step , 936int32_t * ids ,void * stream ) { 937validate (s ,"topk_512" ); 938if (step == nullptr )fail ("topk_512: step is null" ); 939// `cap` is checked against the GEOMETRY'S largest possible width rather than this token's, because this 940// token's is a device value. The two are the same guarantee: `width = min(n_kv, top_k + r - 1)` and 941// `n_kv <= kTopkMaxCells`, so this is the most the kernel can ever write. 942const int64_t width_max = qsa_selection_width (kTopkMaxCells ,s ); 943if (cap < width_max ) { 944 std::fprintf (stderr ,"qsa: topk_512: cap %lld < the largest possible selection width %lld\n" , 945 (long long )cap , (long long )width_max ); 946 std::exit (1 ); 947 } 948// One block, so the launch is already constant; the kernel reads `n_kv` and `width` from `step`. 949 { 950auto exp_props = sycl::ext::oneapi::experimental::properties { 951 sycl::ext::oneapi::experimental::use_root_sync }; 952 953 strata::kprof::kp (strata::q_of (stream ),__FILE__ ,__func__ ,__LINE__ ) 954-> template parallel_for < dpct_kernel_name < class topk_kernel_97d5c9 >> ( 955 sycl::nd_range < 3 > (sycl::range (1 ,1 ,TOPK_THREADS ), 956 sycl::range (1 ,1 ,TOPK_THREADS )), 957exp_props , [= ](sycl::nd_item < 3 > item_ct1 ) { 958topk_kernel (cell_scores ,step ,ids ); 959 }); 960 } 961check_launch ("topk_512" ); 962if (stream == nullptr )check_sync ("topk_512" ); 963} 964 965void kv_gather_step (const uint16_t * k_pool ,const uint16_t * v_pool ,const int32_t * page_table , 966const int32_t * ids ,const int32_t * step ,int64_t max_ids ,const QsaShapes & s , 967uint16_t * k_scratch ,uint16_t * v_scratch ,void * stream ) { 968validate (s ,"kv_gather" ); 969if (step == nullptr )fail ("kv_gather: step is null" ); 970if (max_ids <=0 )return ; 971// THE GRID IS THE CAPACITY. The kernel reads the real `n_ids` from `step` and its `if (i >= total) return;` 972// guard leaves the surplus threads idle. 973const long long total = max_ids * s .n_head_kv * (s .head_dim /4 ); 974 { 975auto exp_props = sycl::ext::oneapi::experimental::properties { 976 sycl::ext::oneapi::experimental::use_root_sync }; 977 978 strata::kprof::kp (strata::q_of (stream ),__FILE__ ,__func__ ,__LINE__ ) 979-> template parallel_for < dpct_kernel_name < class kv_gather_kernel_3473e7 >> ( 980 sycl::nd_range < 3 > (sycl::range (1 ,1 ,grid_for (total ,256 ))* 981 sycl::range (1 ,1 ,256 ), 982 sycl::range (1 ,1 ,256 )), 983exp_props , [= ](sycl::nd_item < 3 > item_ct1 ) { 984kv_gather_kernel (k_pool ,v_pool ,page_table ,ids ,step , 985 (int )s .n_head_kv , (int )s .head_dim , 986 (int )s .page_size ,k_scratch ,v_scratch ); 987 }); 988 } 989check_launch ("kv_gather" ); 990if (stream == nullptr )check_sync ("kv_gather" ); 991} 992 993void qsa_attend_step (const float * q ,const uint16_t * k_scratch , 994const uint16_t * v_scratch ,const int32_t * step , 995int64_t max_ids ,const QsaShapes & s ,float * attn , 996float * weights ,void * stream )try { 997validate (s ,"qsa_attend" ); 998if (step == nullptr )fail ("qsa_attend: step is null" ); 999if (max_ids <=0 )fail ("qsa_attend: max_ids must be positive" ); 1000// THE SHARED SIZE IS THE CAPACITY. Shared memory is part of the LAUNCH CONFIGURATION, so sizing it from 1001// this token's `n_ids` bakes the sequence length in: a captured layer would allocate room for token 1 and 1002// then index past it at token 500. The kernel reads the real count from `step`, so a larger allocation is 1003// exactly what it wants. The opt-in therefore happens once, for the capacity. 1004/* 1005DPCT1083: The size of local memory in the migrated code may be different 1006from the original code. Check that the allocated memory size in the migrated 1007code is correct. 1008*/ 1009const size_t smem = (size_t )(max_ids + 32 )* sizeof (float ); 1010// per DEVICE: the opt-in is a device setting (a layer split runs this on two cards) 1011static size_t s_configured_dev [64 ]= {}; 1012int cur_dev = 0 ; 1013cur_dev = dpct::get_current_device_id (); 1014size_t & s_configured = s_configured_dev [(cur_dev >=0 && cur_dev < 64 ) ?cur_dev :0 ]; 1015if (smem > s_configured ) { 1016int dev = 0 ,max_shared = 0 ; 1017dev = dpct::get_current_device_id (); 1018/* 1019DPCT1019: local_mem_size in SYCL is not a complete equivalent of 1020cudaDevAttrMaxSharedMemoryPerBlockOptin in CUDA. You may need to adjust 1021the code. 1022*/ 1023max_shared = dpct::get_device (dev ).get_local_mem_size (); 1024max_shared = strata::smem_optin_of (max_shared ); 1025if ((int )smem > max_shared ) { 1026 std::fprintf (stderr ,"qsa: qsa_attend: max_ids %lld needs %zu B of shared, over the %d B limit\n" , 1027 (long long )max_ids ,smem ,max_shared ); 1028 std::exit (1 ); 1029 } 1030const dpct::err0 e = 1031/* 1032DPCT1027: The call to cudaFuncSetAttribute was replaced with 0 1033because SYCL currently does not support corresponding setting. 1034*/ 10350 ; 1036 1037s_configured = smem ; 1038 } 1039/* 1040DPCT1049: The work-group size passed to the SYCL kernel may exceed the 1041limit. To get the device limit, query info::device::max_work_group_size. 1042Adjust the work-group size if needed. 1043*/ 1044 { 1045auto exp_props = sycl::ext::oneapi::experimental::properties { 1046 sycl::ext::oneapi::experimental::use_root_sync }; 1047 1048 strata::kprof::kp (strata::q_of (stream ),__FILE__ ,__func__ ,__LINE__ ) 1049-> submit ([& ](sycl::handler & cgh ) { 1050 sycl::local_accessor < uint8_t ,1 > dpct_local_acc_ct1 ( 1051 sycl::range (smem ),cgh ); 1052 1053cgh .parallel_for < 1054dpct_kernel_name < class qsa_attend_kernel_6a355d >> ( 1055 sycl::nd_range < 3 > ( 1056 sycl::range (1 ,1 , (unsigned )s .n_head )* 1057 sycl::range (1 ,1 , (unsigned )s .head_dim ), 1058 sycl::range (1 ,1 , (unsigned )s .head_dim )), 1059exp_props , 1060 [= ](sycl::nd_item < 3 > item_ct1 ) [[sycl ::reqd_sub_group_size ( 106132 )]] { 1062qsa_attend_kernel ( 1063q ,k_scratch ,v_scratch ,step , (int )s .n_head , 1064 (int )s .n_head_kv , (int )s .head_dim ,attn ,weights , 1065dpct_local_acc_ct1 1066 .get_multi_ptr < sycl::access::decorated::no > () 1067 .get ()); 1068 }); 1069 }); 1070 } 1071check_launch ("qsa_attend" ); 1072if (stream == nullptr )check_sync ("qsa_attend" ); 1073} 1074catch (sycl::exception const & exc ) { 1075 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 1076 <<", line:" <<__LINE__ << std::endl ; 1077 std::exit (1 ); 1078} 1079 1080// ================= host entry points ================= 1081 1082void qsa_step_fill (int32_t * host_step ,int64_t pos ,const QsaShapes & s ) { 1083if (host_step == nullptr )return ; 1084if (pos < 0 )fail ("qsa_step_fill: pos < 0" ); 1085// ONE PLACE COMPUTES ALL FOUR, which is the whole reason the step state is a BUFFER rather than four 1086// separate parameters. `n_kv`, `n_bid` and `width` are DERIVED from `pos`, so a caller filling them in 1087// itself could fill them inconsistently - and `qsa_index`'s host guard against exactly that inconsistency 1088// now has a single writer to check against instead of two independent arguments. 1089// 1090// This is the form the LAYER will use: every value a QSA kernel needs derives from one position, so one 1091// H2D per token updates all of them and no entry point takes a per-token scalar. 1092const int64_t n_kv = pos + 1 ; 1093host_step [kStepPos ]= (int32_t )pos ; 1094host_step [kStepNKv ]= (int32_t )n_kv ; 1095host_step [kStepNBid ]= (int32_t ) (n_kv /s .idx_block ); 1096host_step [kStepWidth ]= (int32_t )qsa_selection_width (n_kv ,s ); 1097} 1098 1099void kv_append (uint16_t * k_pool ,uint16_t * v_pool ,const int32_t * page_table ,int64_t pos , 1100const float * kcur ,const float * vcur ,const QsaShapes & s ,void * stream ) { 1101if (pos < 0 ) {validate (s ,"kv_append" );fail ("kv_append: pos < 0" ); } 1102kv_append_step (k_pool ,v_pool ,page_table ,step_upload (pos ,-1 ,s ),kcur ,vcur ,s ,stream ); 1103} 1104 1105void indexer_key_append (const float * raw ,const int32_t * pos_dev ,int32_t pos_base ,const float * w_k_norm , 1106float eps ,const QsaIndexerBuffers & b ,const QsaShapes & s ,const float * cos_tab , 1107const float * sin_tab ,void * stream ) { 1108validate (s ,"indexer_key_append" ); 1109if (pos_dev == nullptr )fail ("indexer_key_append: pos_dev is null" ); 1110if (b .tail == nullptr || b .dead == nullptr || b .pooled == nullptr || b .block_pos == nullptr ) 1111fail ("indexer_key_append: the indexer buffers are not all set (tail/dead/pooled/block_pos)" ); 1112const int threads = (int )s .idx_dim ; 1113/* 1114DPCT1083: The size of local memory in the migrated code may be different 1115from the original code. Check that the allocated memory size in the migrated 1116code is correct. 1117*/ 1118const size_t smem = (size_t )s .idx_dim * sizeof (double ); 1119// **ONE LAUNCH, NO HOST BRANCH ON THE POSITION.** The completion rotation is inside the kernel now. The 1120// arguments here are identical for every token, which is the property a CUDA graph needs: this function can 1121// be captured and replayed, and the position arrives through `pos_dev` like every other kernel's data. 1122/* 1123DPCT1049: The work-group size passed to the SYCL kernel may exceed the 1124limit. To get the device limit, query info::device::max_work_group_size. 1125Adjust the work-group size if needed. 1126*/ 1127 { 1128auto exp_props = sycl::ext::oneapi::experimental::properties { 1129 sycl::ext::oneapi::experimental::use_root_sync }; 1130 dpct::has_capability_or_fail ( 1131 strata::q_of (stream )-> get_device (), 1132 {sycl::aspect::fp64 }); 1133 1134 strata::kprof::kp (strata::q_of (stream ),__FILE__ ,__func__ ,__LINE__ ) 1135-> submit ([& ](sycl::handler & cgh ) { 1136 sycl::local_accessor < uint8_t ,1 > dpct_local_acc_ct1 ( 1137 sycl::range (smem ),cgh ); 1138 1139auto mrope_table_ct14 = mrope_table (); 1140 1141cgh .parallel_for < 1142dpct_kernel_name < class indexer_key_append_kernel_9e74e0 >> ( 1143 sycl::nd_range < 3 > (sycl::range (1 ,1 ,threads ), 1144 sycl::range (1 ,1 ,threads )), 1145exp_props , [= ](sycl::nd_item < 3 > item_ct1 ) { 1146indexer_key_append_kernel ( 1147raw ,pos_dev , (int )pos_base ,w_k_norm ,eps ,b .tail , 1148b .dead ,b .pooled ,b .block_pos , (int )s .idx_dim , 1149 (int )s .idx_block , (int )s .n_rot ,cos_tab ,sin_tab , 1150mrope_table_ct14 , 1151dpct_local_acc_ct1 1152 .get_multi_ptr < sycl::access::decorated::no > () 1153 .get ()); 1154 }); 1155 }); 1156 } 1157check_launch ("indexer_key_append" ); 1158if (stream == nullptr )check_sync ("indexer_key_append" ); 1159} 1160 1161void qsa_index (const float * pooled ,int64_t n_bid ,const float * q_idx ,const float * bias ,const QsaShapes & s , 1162int64_t n_kv ,float * cell_scores ,void * stream ) { 1163validate (s ,"qsa_index" ); 1164if (n_bid < 0 || n_kv <=0 )fail ("qsa_index: n_bid < 0 or n_kv <= 0" ); 1165// `n_kv`, `n_bid` and `width` are DERIVED from one position, so this refuses a caller whose two arguments 1166// disagree rather than launching a kernel that would score the wrong number of blocks. 1167if ((n_kv /s .idx_block )!= n_bid ) { 1168 std::fprintf (stderr ,"qsa: qsa_index: n_bid %lld is not n_kv %lld / r %lld\n" , (long long )n_bid , 1169 (long long )n_kv , (long long )s .idx_block ); 1170 std::exit (1 ); 1171 } 1172// THIS TOKEN'S counts as the CAPACITIES: correct for a direct launch, WRONG in a graph. The layer passes a 1173// constant `max_blocks` from its state instead - see the note in `qsa.hpp`. 1174qsa_index_step (pooled ,q_idx ,bias ,s ,step_upload (n_kv - 1 ,n_kv ,s ),n_bid + 1 ,cell_scores ,stream ); 1175} 1176 1177void topk_512 (const float * cell_scores ,int64_t n_kv ,const QsaShapes & s ,int64_t cap ,int32_t * ids , 1178void * stream ) { 1179validate (s ,"topk_512" ); 1180if (n_kv <=0 )return ; 1181if (n_kv > kTopkMaxCells ) { 1182 std::fprintf (stderr ,"qsa: topk_512: n_kv %lld > kTopkMaxCells %lld (one block; phase 3 replaces this)\n" , 1183 (long long )n_kv , (long long )kTopkMaxCells ); 1184 std::exit (1 ); 1185 } 1186topk_512_step (cell_scores ,s ,cap ,step_upload (n_kv - 1 ,n_kv ,s ),ids ,stream ); 1187} 1188 1189void kv_gather (const uint16_t * k_pool ,const uint16_t * v_pool ,const int32_t * page_table ,const int32_t * ids , 1190int64_t n_ids ,const QsaShapes & s ,uint16_t * k_scratch ,uint16_t * v_scratch ,void * stream ) { 1191validate (s ,"kv_gather" ); 1192if (n_ids <=0 )return ; 1193kv_gather_step (k_pool ,v_pool ,page_table ,ids ,step_upload_width (n_ids ,s ),n_ids ,s ,k_scratch , 1194v_scratch ,stream ); 1195} 1196 1197void qsa_attend (const float * q ,const uint16_t * k_scratch ,const uint16_t * v_scratch ,int64_t n_ids , 1198const QsaShapes & s ,float * attn ,float * weights ,void * stream ) { 1199validate (s ,"qsa_attend" ); 1200if (n_ids < 0 )fail ("qsa_attend: n_ids < 0" ); 1201if (n_ids == 0 ) { 1202// The empty selection goes through the kernel's own zero path; `max_ids` must still be positive, so the 1203// wrapper gives it the geometry's capacity rather than 0. 1204qsa_attend_step (q ,k_scratch ,v_scratch ,step_upload_width (0 ,s ), 1205qsa_selection_width (kTopkMaxCells ,s ),s ,attn ,weights ,stream ); 1206return ; 1207 } 1208qsa_attend_step (q ,k_scratch ,v_scratch ,step_upload_width (n_ids ,s ),n_ids ,s ,attn ,weights ,stream ); 1209} 1210 1211/// The same multiply as `qsa_gate_apply_kernel` WITHOUT the fp16 round - see the header for why the caller 1212/// whose weight is a K-quant needs the f32 form. Identical arithmetic up to the last step. 1213__dpct_inline__ void qsa_gate_apply_f32_kernel (const float * __restrict__attn , 1214const float * __restrict__q_full , 1215int n_head ,int head_dim , 1216float * __restrict__out ) { 1217auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item < 3 > (); 1218const long long i = 1219item_ct1 .get_group (2 )* (long long )item_ct1 .get_local_range (2 )+ 1220item_ct1 .get_local_id (2 ); 1221if (i >= (long long )n_head * head_dim )return ; 1222const int h = (int ) (i /head_dim ),d = (int ) (i %head_dim ); 1223const double g = (double )q_full [((size_t )h * 2 * head_dim )+ head_dim + d ];// the SECOND half 1224const double sig = 1.0 / (1.0 + sycl::exp (- g )); 1225out [i ]= (float ) ((double )attn [i ]* sig ); 1226} 1227 1228void qsa_gate_apply_f32 (const float * attn ,const float * q_full ,const QsaShapes & s ,float * out ,void * stream ) { 1229validate (s ,"qsa_gate_apply_f32" ); 1230const long long n = s .n_head * s .head_dim ; 1231 { 1232auto exp_props = sycl::ext::oneapi::experimental::properties { 1233 sycl::ext::oneapi::experimental::use_root_sync }; 1234 dpct::has_capability_or_fail ( 1235 strata::q_of (stream )-> get_device (), 1236 {sycl::aspect::fp64 }); 1237 1238 strata::kprof::kp (strata::q_of (stream ),__FILE__ ,__func__ ,__LINE__ ) 1239-> template parallel_for < 1240dpct_kernel_name < class qsa_gate_apply_f32_kernel_7cff4f >> ( 1241 sycl::nd_range < 3 > (sycl::range (1 ,1 ,grid_for (n ,256 ))* 1242 sycl::range (1 ,1 ,256 ), 1243 sycl::range (1 ,1 ,256 )), 1244exp_props , [= ](sycl::nd_item < 3 > item_ct1 ) { 1245qsa_gate_apply_f32_kernel (attn ,q_full , (int )s .n_head , 1246 (int )s .head_dim ,out ); 1247 }); 1248 } 1249check_launch ("qsa_gate_apply_f32" ); 1250if (stream == nullptr )check_sync ("qsa_gate_apply_f32" ); 1251} 1252 1253void qsa_gate_apply (const float * attn ,const float * q_full ,const QsaShapes & s ,uint16_t * out ,void * stream ) { 1254validate (s ,"qsa_gate_apply" ); 1255const long long n = s .n_head * s .head_dim ; 1256 { 1257auto exp_props = sycl::ext::oneapi::experimental::properties { 1258 sycl::ext::oneapi::experimental::use_root_sync }; 1259 dpct::has_capability_or_fail ( 1260 strata::q_of (stream )-> get_device (), 1261 {sycl::aspect::fp64 }); 1262 1263 strata::kprof::kp (strata::q_of (stream ),__FILE__ ,__func__ ,__LINE__ ) 1264-> template parallel_for < 1265dpct_kernel_name < class qsa_gate_apply_kernel_650dec >> ( 1266 sycl::nd_range < 3 > (sycl::range (1 ,1 ,grid_for (n ,256 ))* 1267 sycl::range (1 ,1 ,256 ), 1268 sycl::range (1 ,1 ,256 )), 1269exp_props , [= ](sycl::nd_item < 3 > item_ct1 ) { 1270qsa_gate_apply_kernel (attn ,q_full , (int )s .n_head , 1271 (int )s .head_dim ,out ); 1272 }); 1273 } 1274check_launch ("qsa_gate_apply" ); 1275if (stream == nullptr )check_sync ("qsa_gate_apply" ); 1276} 1277 1278}// namespace strata::kernels