dpct of6ac1a2cand2ca1b66, normalized, kernel-name hashes canonicalized to the port's, then git merge-file into sycl/: 49 files, 10 with real conflicts. - verify: upstream's set_commit_async/wait_commit on the port's deferred commit (wait_commit = commit_finish); copy_logits on the queue - fused_gr: upstream's split/staged read variants merged but unused by the port's read; their per-card self-test segfaults on the B70, so on SYCL it runs only with STRATA_HC_CHECK=1. The port's split-norm kernel renamed (upstream has one of the same name); two colliding kernel names renamed - fixups.py: fused_gr's per-block local-memory query - hand files: mtp.cpp, verify.cpp, ple_reader.cpp (keep-alive reads + trace) - qsa_prompt_attn_parity turns on the XMX kernel it checks - version 0.1.32 Tested on the B70: build clean; Coder (19 / 2,184-token prompts) and IQ2_XS outputs identical to 0.1.31 at the same speed (78.1 / 75.7, 58.5 tok/s); 40K prompt 1,201 tok/s, decode 65.1; kv_hybrid, qsa_prompt_attn, qsa, gr, kv_q4, kv_q8, rope, router, sampler, quantize_act parity pass.
1278 lines
61 KiB
C++
1278 lines
61 KiB
C++
// src/kernels/cuda/qsa.cu - P2.S2: the QSA cache, indexer and attention (see include/strata/kernels/qsa.hpp).
|
|
//
|
|
// The header documents the layouts and the scope; this file documents the four decisions that are about the
|
|
// KERNEL rather than about the interface.
|
|
//
|
|
// 1. THE THRESHOLD SEARCH IN `topk_512` RATHER THAN A SORT. The selection has to reproduce `ggml_top_k` on the
|
|
// masked per-cell scores with the reference's tie rule (ascending index), and it has to be EXACT: a
|
|
// different selected set is a different attention input, and `docs/capture-format.md` L127 gives
|
|
// `indexer_ids` no tolerance. The kernel therefore computes the width-th largest score as a 32-bit
|
|
// "order key" by binary lifting (32 monotone passes with `count(key >= cand) >= width`), and then emits -
|
|
// in ONE ascending walk - every cell strictly above it and the first `width - c_gt` cells equal to it. That
|
|
// is provably the same set as sorting by (score desc, index asc) and taking the first width, it needs no
|
|
// scratch and no sort, it is deterministic, and it is the reason `kTopkMaxCells` exists: the whole selection
|
|
// runs in ONE block so the ascending walk is a chunked scan rather than a second global pass. Phase 3
|
|
// replaces it with a radix select; this one is the thing that radix select has to agree with.
|
|
//
|
|
// 2. ONE BLOCK PER HEAD IN `qsa_attend`, SCORES IN SHARED MEMORY. n_ids reaches 2051, so a per-head score
|
|
// vector is 8 KB and 24 heads are 24 blocks: the whole attention is 24 blocks x 256 threads, which is a
|
|
// small grid, but it is also exactly the shape the source uses (one flash tile per query head) and it keeps
|
|
// the softmax's three passes over the scores in shared memory instead of in global. The score loop has one
|
|
// thread per CELL walking the 256 dims sequentially, which reads 16-byte-vectorisable half2 runs; the value
|
|
// loop has one thread per DIM walking the cells, whose warp-wide reads are contiguous within a cell. Both
|
|
// are coalesced for the layout the gather produces.
|
|
//
|
|
// 3. NO `__float2half`. `f16_from_f32` from f16_bits.hpp, for the reason round 193 recorded: `__float2half`
|
|
// produced 0x2600 for 0x26DB and 0x3C01 for exactly 1.0. The parity test checks that converter against
|
|
// vectors generated by numpy's float16, which is an oracle sharing no code with it.
|
|
//
|
|
// 4. THE POOLING ARITHMETIC IS IN DOUBLE AND ORDER-FIXED. `pooled` and the spare key are compared BIT-EXACT
|
|
// against the reference (the spare key's rotation is at position 0, where the f32 rope kernel is an exact
|
|
// identity, so the comparison is not weakened by the rope). That needs the same summation order on both
|
|
// sides: the `r` raw keys are added in CELL order, the sum of squares runs d = 0..idx_dim-1 sequentially,
|
|
// and `__dadd_rn`/`__dmul_rn` block FMA contraction, which would otherwise fuse `ss + m*m` into one
|
|
// operation with no intermediate rounding and land one ulp away from the host.
|
|
//
|
|
// THE `d` IN THOSE NAMES IS NOT COSMETIC. The first version wrote `__fadd_rn`/`__fmul_rn`, which are
|
|
// the SINGLE-precision intrinsics: the compiler converted each double operand to float, operated
|
|
// there, and converted back, so the whole pooling arithmetic ran in single precision - `ss` held only
|
|
// float precision (121.82236480712891 on the device against 121.82236342931094 in the reference).
|
|
// Every comparison still passed at any sane tolerance, the spare key landing 0.4 f32 ulp away; only a
|
|
// BIT-EXACT assertion plus a full-precision probe of the intermediate found it. That is the strongest
|
|
// argument in this file for keeping both.
|
|
#define DPCT_PROFILING_ENABLED
|
|
#include <sycl/sycl.hpp>
|
|
#include <dpct/dpct.hpp>
|
|
#include "strata/sycl_queue.hpp"
|
|
#include "strata/core/emulate.hpp"
|
|
#include "strata/kernels/qsa.hpp"
|
|
|
|
#include "strata/kernels/f16_bits.hpp"
|
|
#include "strata/kernels/kv_stream.hpp"
|
|
#include "strata/kernels/rope.hpp"
|
|
#include "strata/kernels/mrope.hpp"
|
|
|
|
#include <cfloat>
|
|
#include <cmath>
|
|
#include <cstdio>
|
|
#include <cstdlib>
|
|
#include <cstring>
|
|
|
|
namespace strata::kernels {
|
|
namespace {
|
|
|
|
constexpr int THREADS = 128;
|
|
|
|
void fail(const char* what) {
|
|
std::fprintf(stderr, "qsa: %s\n", what);
|
|
std::exit(1);
|
|
}
|
|
|
|
void check_launch(const char* what) {
|
|
/*
|
|
DPCT1010: SYCL uses exceptions to report errors and does not use the
|
|
error codes. The cudaGetLastError function call was replaced with 0. You
|
|
need to rewrite this code.
|
|
*/
|
|
const dpct::err0 e = 0;
|
|
}
|
|
|
|
/// The SYNCHRONOUS entry points must check their own wait. Without this the sticky error from a kernel that
|
|
/// faulted becomes visible only at the NEXT call's `cudaGetLastError()`, which then names the wrong kernel -
|
|
/// exactly the mis-attribution that made round 198's first `kv_append` failure look like a later one.
|
|
void check_sync(const char *what) try {
|
|
const dpct::err0 e =
|
|
DPCT_CHECK_ERROR(dpct::get_current_device().queues_wait_and_throw());
|
|
}
|
|
catch (sycl::exception const &exc) {
|
|
std::cerr << exc.what() << "Exception caught at file:" << __FILE__
|
|
<< ", line:" << __LINE__ << std::endl;
|
|
std::exit(1);
|
|
}
|
|
|
|
/// Geometry validation. A silently wrong `head_dim % 4` would corrupt the gather's uint2 copy and a silently
|
|
/// wrong `n_head % n_head_kv` would produce a plausible attention with the wrong key, so both are refused.
|
|
void validate(const QsaShapes& s, const char* who) {
|
|
if (s.n_head <= 0 || s.n_head_kv <= 0 || s.head_dim <= 0 || s.idx_dim <= 0 || s.idx_n_head <= 0 ||
|
|
s.idx_block < 2 || s.page_size < 1) {
|
|
std::fprintf(stderr, "qsa: %s: geometry is not set up\n", who);
|
|
std::exit(1);
|
|
}
|
|
if (s.n_head % s.n_head_kv != 0) {
|
|
std::fprintf(stderr, "qsa: %s: n_head %lld is not a multiple of n_head_kv %lld\n", who,
|
|
(long long) s.n_head, (long long) s.n_head_kv);
|
|
std::exit(1);
|
|
}
|
|
if (s.head_dim % 4 != 0) {
|
|
std::fprintf(stderr, "qsa: %s: head_dim %lld must be a multiple of 4 (the gather copies uint2)\n", who,
|
|
(long long) s.head_dim);
|
|
std::exit(1);
|
|
}
|
|
if (s.n_rot <= 0 || s.n_rot % 2 != 0 || s.n_rot > s.head_dim || s.n_rot > s.idx_dim) {
|
|
std::fprintf(stderr, "qsa: %s: n_rot %lld must be even and <= head_dim %lld and idx_dim %lld\n", who,
|
|
(long long) s.n_rot, (long long) s.head_dim, (long long) s.idx_dim);
|
|
std::exit(1);
|
|
}
|
|
if (s.idx_n_head > 32) {
|
|
std::fprintf(stderr, "qsa: %s: idx_n_head %lld > 32 (one warp per indexer head)\n", who,
|
|
(long long) s.idx_n_head);
|
|
std::exit(1);
|
|
}
|
|
}
|
|
|
|
__dpct_inline__ float h2f(uint16_t bits) { return f32_from_f16(bits); }
|
|
|
|
// ================= 1. kv_append =================
|
|
|
|
__dpct_inline__ void
|
|
kv_append_kernel(uint16_t *__restrict__ k_pool, uint16_t *__restrict__ v_pool,
|
|
const int32_t *__restrict__ table,
|
|
const int32_t *__restrict__ step,
|
|
const float *__restrict__ kcur, const float *__restrict__ vcur,
|
|
int kv_heads, int head_dim, int page_size, KvHostPools host) {
|
|
/*
|
|
DPCT1098: The '*' expression is used instead of the __ldg call. These
|
|
two expressions do not provide the exact same functionality. Check the
|
|
generated code for potential precision and/or performance issues.
|
|
*/
|
|
auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
|
|
const long long pos = (long long)*(step + kStepPos);
|
|
const int i = item_ct1.get_group(2) * item_ct1.get_local_range(2) +
|
|
item_ct1.get_local_id(2);
|
|
if (i >= kv_heads * head_dim) return;
|
|
const int h = i / head_dim, d = i - h * head_dim;
|
|
// `[page][kv_head][page_size][head_dim]`: one head's consecutive cells are contiguous inside a page.
|
|
// KV streaming: the host copy (identity layout) always, the VRAM page only if the block is resident.
|
|
const long long page = (long long) table[pos / page_size];
|
|
if (page >= 0) {
|
|
const long long row = (page * kv_heads + h) * page_size + (pos % page_size);
|
|
k_pool[row * head_dim + d] = f16_from_f32(kcur[i]);
|
|
v_pool[row * head_dim + d] = f16_from_f32(vcur[i]);
|
|
}
|
|
if (host.k_pool != nullptr) {
|
|
const long long row = ((pos / page_size) * kv_heads + h) * page_size + (pos % page_size);
|
|
host.k_pool[row * head_dim + d] = f16_from_f32(kcur[i]);
|
|
host.v_pool[row * head_dim + d] = f16_from_f32(vcur[i]);
|
|
}
|
|
}
|
|
|
|
// ================= 2. indexer_key_append =================
|
|
|
|
/// Appends the raw key, and on a block completion pools AND ROTATES the pooled row. One thread per indexer
|
|
/// dim, shared `mean` in double.
|
|
///
|
|
/// **THE ROTATION IS INSIDE THIS KERNEL, AND THAT IS WHAT MAKES THE WHOLE FUNCTION CAPTURABLE.** It used to be
|
|
/// a second launch from the host wrapper, guarded by `if (pos % idx_block == idx_block - 1)` - a HOST branch on
|
|
/// `pos`, which forced `pos` to be a host scalar, which meant a captured graph would replay the first token's
|
|
/// position forever. Doing it here reads the position from `pos_dev` like every other kernel, so the grid and
|
|
/// the arguments are the same for every token and the graph replays correctly.
|
|
__dpct_inline__ void indexer_key_append_kernel(
|
|
const float *__restrict__ raw, const int32_t *__restrict__ pos_dev,
|
|
int pos_base, const float *__restrict__ w_k_norm, float eps,
|
|
float *__restrict__ tail, float *__restrict__ dead,
|
|
float *__restrict__ pooled, int32_t *__restrict__ block_pos, int idx_dim,
|
|
int r, int n_rot, const float *__restrict__ cos_tab,
|
|
const float *__restrict__ sin_tab, const int32_t *__restrict__ mtab,
|
|
uint8_t *dpct_local) {
|
|
auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
|
|
auto s_mean = (double *)dpct_local; // idx_dim doubles
|
|
const int d = item_ct1.get_local_id(2);
|
|
/*
|
|
DPCT1098: The '*' expression is used instead of the __ldg call. These
|
|
two expressions do not provide the exact same functionality. Check the
|
|
generated code for potential precision and/or performance issues.
|
|
*/
|
|
const int pos = (int)*pos_dev;
|
|
const int slot = pos % r;
|
|
|
|
// The RAW tail: a cell that COMPLETES a block is not stored, because the pool below consumes it directly.
|
|
// That is what makes `idx_block - 1` rows enough.
|
|
if (slot < r - 1) tail[(size_t) slot * idx_dim + d] = raw[d];
|
|
|
|
// The spare slot's key is `rms_norm(raw[0])`, which is CONSTANT for the sequence and is the only reason
|
|
// cell 0's raw key has to be kept: the three-row tail no longer holds it after the first block.
|
|
if (pos == 0) {
|
|
double p = (double) raw[d];
|
|
double ss = 0.0;
|
|
// Same order as the pooled path, so the two are comparable: sum of squares over the dims, sequential.
|
|
// Every thread computes the same `ss` and uses only its own output element.
|
|
//
|
|
// `__dadd_rn`/`__dmul_rn`, NOT `__fadd_rn`/`__fmul_rn`: the `f` names are the SINGLE-precision
|
|
// intrinsics, and using them on doubles silently rounds every operation to float. `ss` then carries
|
|
// only float precision (121.82236480712891 against the reference's 121.82236342931094) and the spare
|
|
// key comes out 0.4 f32 ulp away - close enough that only a BIT-EXACT assertion notices. `__ddiv_rn`
|
|
// and `__dsqrt_rn` pin the reciprocal square root for the same reason.
|
|
for (int i = 0; i < idx_dim; ++i) {
|
|
const double v = (double) raw[i];
|
|
/*
|
|
DPCT1013: The rounding mode could not be specified and the
|
|
generated code may have different accuracy than the original code.
|
|
Verify the correctness. SYCL math built-in function rounding mode is
|
|
aligned with OpenCL C 1.2 standard.
|
|
*/
|
|
ss = ss + v * v;
|
|
}
|
|
/*
|
|
DPCT1013: The rounding mode could not be specified and the generated
|
|
code may have different accuracy than the original code. Verify the
|
|
correctness. SYCL math built-in function rounding mode is aligned with
|
|
OpenCL C 1.2 standard.
|
|
*/
|
|
const double inv = 1.0 / sycl::sqrt(ss / (double)idx_dim + (double)eps);
|
|
float y = (float) (p * inv * (double) w_k_norm[d]);
|
|
// The spare rotates at position 0 - ALWAYS row 0 of the table, whatever `pos_base` is, as the native
|
|
// indexer's spare does. At angle 0 the sine is exactly 0 in every scaling (sin(0) * mscale), so the
|
|
// pair rotation reduces to `v * cos_tab[pair]` with no partner element to read (and no barrier).
|
|
// Unscaled, row 0 is exactly (1, 0) and `v * 1.0f` is `v` bit for bit - today's value, which the
|
|
// parity test holds bit-exact. Under YaRN row 0 is (mscale, 0): the rotated dims carry the magnitude
|
|
// correction exactly like every other pooled row and like the native kernel's spare (the unrotated
|
|
// dims pass through, as in the rotation of the completed blocks below). Skipping the rotation here,
|
|
// as this kernel once did, left `dead` and `pooled[0]` the only unscaled keys of a scaled cache.
|
|
if (d < n_rot) y *= cos_tab[d % (n_rot / 2)];
|
|
dead[d] = y;
|
|
pooled[d] = y;
|
|
}
|
|
|
|
if (slot != r - 1) return;
|
|
/*
|
|
DPCT1065: Consider replacing sycl::nd_item::barrier() with
|
|
sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
|
|
performance if there is no access to global memory.
|
|
*/
|
|
item_ct1.barrier(); // the tail rows this thread is about to read are
|
|
// written above
|
|
|
|
// The mean of this block's r raw keys, in CELL order: the r-1 tail rows (slots 0..r-2) then the incoming
|
|
// cell (slot r-1). The sum of r f32 values is exact in double, so the mean's order cannot matter here -
|
|
// but the order of the SUM OF SQUARES below can, and it is fixed to d ascending on both sides.
|
|
double m = 0.0;
|
|
/*
|
|
DPCT1013: The rounding mode could not be specified and the generated code
|
|
may have different accuracy than the original code. Verify the correctness. SYCL
|
|
math built-in function rounding mode is aligned with OpenCL C 1.2 standard.
|
|
*/
|
|
#pragma unroll
|
|
for (int j = 0; j < r - 1; ++j)
|
|
m = m + (double)tail[(size_t)j * idx_dim + d];
|
|
/*
|
|
DPCT1013: The rounding mode could not be specified and the generated
|
|
code may have different accuracy than the original code. Verify the
|
|
correctness. SYCL math built-in function rounding mode is aligned with
|
|
OpenCL C 1.2 standard.
|
|
*/
|
|
m = m + (double)raw[d];
|
|
m = m / (double) r;
|
|
s_mean[d] = m;
|
|
/*
|
|
DPCT1065: Consider replacing sycl::nd_item::barrier() with
|
|
sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
|
|
performance if there is no access to global memory.
|
|
*/
|
|
item_ct1.barrier();
|
|
|
|
double ss = 0.0;
|
|
/*
|
|
DPCT1013: The rounding mode could not be specified and the generated code
|
|
may have different accuracy than the original code. Verify the correctness. SYCL
|
|
math built-in function rounding mode is aligned with OpenCL C 1.2 standard.
|
|
*/
|
|
#pragma unroll
|
|
for (int i = 0; i < idx_dim; ++i) ss = ss + s_mean[i] * s_mean[i];
|
|
/*
|
|
DPCT1013: The rounding mode could not be specified and the generated
|
|
code may have different accuracy than the original code. Verify the
|
|
correctness. SYCL math built-in function rounding mode is aligned with
|
|
OpenCL C 1.2 standard.
|
|
*/
|
|
const double inv = 1.0 / sycl::sqrt(ss / (double)idx_dim + (double)eps);
|
|
|
|
const int b = pos / r;
|
|
pooled[(size_t) b * idx_dim + d] = (float) (m * inv * (double) w_k_norm[d]);
|
|
// The spare slot MOVES to b+1 and is rewritten with the same constant value.
|
|
pooled[(size_t) (b + 1) * idx_dim + d] = dead[d];
|
|
// The rotation position for this row, kept because a capture reader and the debug dumps want it. It is the
|
|
// block's first cell's POSITION, `pos_base + b*r`, and NOT the cell index `b*r`.
|
|
if (d == 0) *block_pos = (int32_t) (pos_base + b * r);
|
|
/*
|
|
DPCT1065: Consider replacing sycl::nd_item::barrier() with
|
|
sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
|
|
performance if there is no access to global memory.
|
|
*/
|
|
item_ct1.barrier(); // the row is complete only now; the rotation below
|
|
// reads TWO elements of it
|
|
|
|
// ---- the rotation of the row that just completed, IN PLACE.
|
|
//
|
|
// `i` pairs with `i + half`, so only the first `half` threads do any work - but EVERY thread must reach the
|
|
// barrier above, which is why the guard is here and not around the whole block's tail.
|
|
//
|
|
// The position is the BLOCK'S FIRST cell (`ref/qsa.py` PROPERTY 4: rotating at the block's last cell keeps
|
|
// every shape and every magnitude), and it comes from `pos_base`, which is constant for a sequence.
|
|
const int half = n_rot / 2;
|
|
if (d < half) {
|
|
float* row = pooled + (size_t) b * idx_dim;
|
|
const size_t toff = (size_t) mrope_pos(mtab, pos_base + b * r, d) * half;
|
|
// THE SAME `rope_neox_pair` THE STANDALONE ROPE KERNEL USES. A second transcription of the pairing is
|
|
// what this project keeps finding written down wrong.
|
|
rope_neox_pair(row[d], row[half + d], cos_tab[toff + d], sin_tab[toff + d], row[d], row[half + d]);
|
|
}
|
|
}
|
|
|
|
// ================= 3. qsa_index =================
|
|
|
|
/// One warp per indexer head, one block per pooled row; thread 0 sums the relu'd dots IN HEAD ORDER and maps
|
|
/// the row's score onto its cells. The reference's Relu is PER HEAD, so the dots cannot be summed first.
|
|
__dpct_inline__ void qsa_index_kernel(const float *__restrict__ pooled,
|
|
const float *__restrict__ q_idx,
|
|
const float *__restrict__ bias,
|
|
int idx_n_head, int idx_dim, long long r,
|
|
const int32_t *__restrict__ step,
|
|
float *__restrict__ cell_scores) {
|
|
/*
|
|
DPCT1098: The '*' expression is used instead of the __ldg call. These
|
|
two expressions do not provide the exact same functionality. Check the
|
|
generated code for potential precision and/or performance issues.
|
|
*/
|
|
auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
|
|
const long long n_bid = (long long)*(step + kStepNBid);
|
|
/*
|
|
DPCT1098: The '*' expression is used instead of the __ldg call. These
|
|
two expressions do not provide the exact same functionality. Check the
|
|
generated code for potential precision and/or performance issues.
|
|
*/
|
|
const long long n_kv = (long long)*(step + kStepNKv);
|
|
auto &s_dot =
|
|
*sycl::ext::oneapi::group_local_memory_for_overwrite<double[32]>(
|
|
sycl::ext::oneapi::this_work_item::get_work_group<3>());
|
|
const long long b = item_ct1.get_group(2);
|
|
// A BLOCK PAST THE COMPLETED-BLOCK COUNT MUST DO NOTHING. This is what lets the LAYER launch a CONSTANT
|
|
// grid of the maximum block count instead of this token's `n_bid + 1`: a grid sized from a per-token value
|
|
// is a per-token LAUNCH CONFIGURATION, and a CUDA graph bakes those in exactly as it bakes in an argument.
|
|
// Without this guard, a capacity-sized grid would score pooled rows that have not been written yet -
|
|
// reading zeros and producing a plausible score for a block that does not exist.
|
|
if (b > n_bid) return;
|
|
const int wid = item_ct1.get_local_id(2) >> 5,
|
|
lane = item_ct1.get_local_id(2) & 31;
|
|
if (wid == 0) s_dot[lane] = 0.0; // thread 0 reads all idx_n_head entries; zero the unused ones
|
|
item_ct1.barrier(sycl::access::fence_space::local_space);
|
|
|
|
double acc = 0.0;
|
|
#pragma unroll
|
|
for (int d = lane; d < idx_dim; d += 32)
|
|
/*
|
|
DPCT1013: The rounding mode could not be specified and the generated
|
|
code may have different accuracy than the original code. Verify the
|
|
correctness. SYCL math built-in function rounding mode is aligned with
|
|
OpenCL C 1.2 standard.
|
|
*/
|
|
acc = acc + (double)pooled[(size_t)b * idx_dim + d] *
|
|
(double)q_idx[(size_t)wid * idx_dim + d];
|
|
/*
|
|
DPCT1108: '__shfl_xor_sync' was migrated with the experimental feature
|
|
masked sub_group function which may not be supported by all compilers or
|
|
runtimes. You may need to adjust the code.
|
|
*/
|
|
/*
|
|
DPCT1013: The rounding mode could not be specified and the generated code
|
|
may have different accuracy than the original code. Verify the correctness. SYCL
|
|
math built-in function rounding mode is aligned with OpenCL C 1.2 standard.
|
|
*/
|
|
#pragma unroll
|
|
for (int o = 16; o > 0; o >>= 1) acc =
|
|
acc + dpct::experimental::permute_sub_group_by_xor(
|
|
0xffffffffu,
|
|
sycl::ext::oneapi::this_work_item::get_sub_group(), acc, o);
|
|
if (lane == 0) s_dot[wid] = acc;
|
|
item_ct1.barrier(sycl::access::fence_space::local_space);
|
|
|
|
if (item_ct1.get_local_id(2) != 0) return;
|
|
double score = 0.0;
|
|
#pragma unroll
|
|
for (int h = 0; h < idx_n_head; ++h) score +=
|
|
(s_dot[h] > 0.0) ? s_dot[h] : 0.0;
|
|
if (bias != nullptr) score += (double) bias[b];
|
|
// cell_block: cells of block b for b < n_bid, and the WHOLE incomplete tail for b == n_bid
|
|
long long lo = b * r, hi = lo + r;
|
|
if (b == n_bid) hi = n_kv;
|
|
if (hi > n_kv) hi = n_kv;
|
|
// llama-memory-hybrid-idx.cpp::set_input_qsa gives incomplete-tail cells
|
|
// a finite +1e9 bias before top-k. Read the current step on every replay:
|
|
// the spare row becomes an ordinary block as soon as its fourth cell arrives.
|
|
float sc = (float) score;
|
|
if (b == n_bid && n_kv % r != 0) sc += 1e9f;
|
|
#pragma unroll
|
|
for (long long j = lo; j < hi; ++j) cell_scores[j] = sc;
|
|
}
|
|
|
|
// ================= 4. topk_512 =================
|
|
|
|
/// Total order over f32 as an unsigned key, so one integer comparison orders scores with numpy's float
|
|
/// semantics. `+ 0.0f` maps -0.0 to +0.0 because numpy treats them as EQUAL (and would break the tie by
|
|
/// index), while the raw bit pattern orders them. A NaN is mapped to 0, below every real key, i.e. never
|
|
/// selected - numpy sorts NaN LAST, and silently selecting one would be worse than the disagreement.
|
|
__dpct_inline__ uint32_t order_key(float s) {
|
|
const float v = s + 0.0f;
|
|
if (!(v == v)) return 0u;
|
|
uint32_t b;
|
|
memcpy(&b, &v, 4);
|
|
return (b & 0x80000000u) ? ~b : (b | 0x80000000u);
|
|
}
|
|
|
|
constexpr int TOPK_THREADS = 256;
|
|
|
|
/*
|
|
DPCT1110: The total declared local variable size in device function
|
|
topk_kernel exceeds 128 bytes and may cause high register pressure. Consult with
|
|
your hardware vendor to find the total register size available and adjust the
|
|
code, or use smaller sub-group size to avoid high register pressure.
|
|
*/
|
|
__dpct_inline__ void topk_kernel(const float *__restrict__ scores,
|
|
const int32_t *__restrict__ step,
|
|
int *__restrict__ out_ids) {
|
|
/*
|
|
DPCT1098: The '*' expression is used instead of the __ldg call. These
|
|
two expressions do not provide the exact same functionality. Check the
|
|
generated code for potential precision and/or performance issues.
|
|
*/
|
|
auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
|
|
const long long n_kv = (long long)*(step + kStepNKv);
|
|
/*
|
|
DPCT1098: The '*' expression is used instead of the __ldg call. These
|
|
two expressions do not provide the exact same functionality. Check the
|
|
generated code for potential precision and/or performance issues.
|
|
*/
|
|
const long long width = (long long)*(step + kStepWidth);
|
|
auto &s_a =
|
|
*sycl::ext::oneapi::group_local_memory_for_overwrite<int[TOPK_THREADS]>(
|
|
sycl::ext::oneapi::this_work_item::get_work_group<3>());
|
|
auto &s_b =
|
|
*sycl::ext::oneapi::group_local_memory_for_overwrite<int[TOPK_THREADS]>(
|
|
sycl::ext::oneapi::this_work_item::get_work_group<3>());
|
|
auto &s_cgt =
|
|
*sycl::ext::oneapi::group_local_memory_for_overwrite<long long>(
|
|
sycl::ext::oneapi::this_work_item::get_work_group<3>());
|
|
const int t = item_ct1.get_local_id(2);
|
|
const long long chunk = (n_kv + TOPK_THREADS - 1) / TOPK_THREADS;
|
|
const long long lo = (long long) t * chunk;
|
|
long long hi = lo + chunk;
|
|
if (hi > n_kv) hi = n_kv;
|
|
|
|
// ---- binary lifting: the largest key v with count(key >= v) >= width. Monotone in v, so setting the
|
|
// bits from the top down lands on exactly that value, and count(>= v) >= width > count(>= v+1).
|
|
uint32_t v = 0u;
|
|
for (int bit = 31; bit >= 0; --bit) {
|
|
const uint32_t cand = v | (1u << bit);
|
|
int c = 0;
|
|
#pragma unroll
|
|
for (long long j = lo; j < hi;
|
|
++j) if (order_key(scores[j]) >= cand)++ c;
|
|
s_a[t] = c;
|
|
/*
|
|
DPCT1118: SYCL group functions and algorithms must be encountered in
|
|
converged control flow. You may need to adjust the code.
|
|
*/
|
|
item_ct1.barrier(sycl::access::fence_space::local_space);
|
|
#pragma unroll
|
|
for (int s = TOPK_THREADS / 2; s > 0; s >>= 1) {
|
|
if (t < s) s_a[t] += s_a[t + s];
|
|
/*
|
|
DPCT1118: SYCL group functions and algorithms must be
|
|
encountered in converged control flow. You may need to adjust the
|
|
code.
|
|
*/
|
|
item_ct1.barrier(sycl::access::fence_space::local_space);
|
|
}
|
|
const int tot = s_a[0];
|
|
/*
|
|
DPCT1118: SYCL group functions and algorithms must be encountered in
|
|
converged control flow. You may need to adjust the code.
|
|
*/
|
|
item_ct1.barrier(
|
|
sycl::access::fence_space::local_space); // before the next round
|
|
// overwrites s_a
|
|
if (tot >= (int) width) v = cand;
|
|
}
|
|
const uint32_t thr = v;
|
|
|
|
// ---- counts and their exclusive prefixes. The prefixes are computed by thread 0 in one walk, which is
|
|
// 256 iterations ONCE per kernel and removes 2 log-steps of scan machinery from a path that is already
|
|
// 32 passes deep.
|
|
int gt = 0, eq = 0;
|
|
for (long long j = lo; j < hi; ++j) {
|
|
const uint32_t k = order_key(scores[j]);
|
|
if (k > thr) ++gt;
|
|
else if (k == thr) ++eq;
|
|
}
|
|
s_a[t] = gt;
|
|
s_b[t] = eq;
|
|
item_ct1.barrier(sycl::access::fence_space::local_space);
|
|
if (t == 0) {
|
|
long long ag = 0, ae = 0;
|
|
for (int i = 0; i < TOPK_THREADS; ++i) {
|
|
const int g = s_a[i], e = s_b[i];
|
|
s_a[i] = (int) ag;
|
|
s_b[i] = (int) ae;
|
|
ag += g;
|
|
ae += e;
|
|
}
|
|
s_cgt = ag; // how many are strictly above the threshold, i.e. where the equals start
|
|
}
|
|
item_ct1.barrier(sycl::access::fence_space::local_space);
|
|
// THE RANK VS THE COUNT. `off_eq` is how many equal-to-threshold cells come BEFORE this chunk, and it is
|
|
// compared against `eq_budget`, the number of them the selection has room for. The first version wrote
|
|
// `c_gt + prefix_eq` - where an equal cell would land in a "greater-than first, then equal" LAYOUT - and
|
|
// compared THAT against the budget. With distinct scores `c_gt == width` and `eq_budget == 0`, so nothing
|
|
// was ever selected at the threshold and the kernel emitted `width` ids with one missing and one stale.
|
|
// Every all-equal fixture passed, because there `c_gt == 0` and the two readings coincide.
|
|
const long long off_eq = s_b[t];
|
|
const long long eq_budget = width - s_cgt;
|
|
|
|
// ---- how many this chunk selects, so the ascending walk can be scattered into place
|
|
int sel = 0;
|
|
{
|
|
long long e = off_eq;
|
|
for (long long j = lo; j < hi; ++j) {
|
|
const uint32_t k = order_key(scores[j]);
|
|
if (k > thr) ++sel;
|
|
else if (k == thr && e < eq_budget) { ++sel; ++e; }
|
|
}
|
|
}
|
|
s_a[t] = sel;
|
|
item_ct1.barrier(sycl::access::fence_space::local_space);
|
|
if (t == 0) {
|
|
long long a = 0;
|
|
for (int i = 0; i < TOPK_THREADS; ++i) {
|
|
const int c = s_a[i];
|
|
s_a[i] = (int) a;
|
|
a += c;
|
|
}
|
|
}
|
|
item_ct1.barrier(sycl::access::fence_space::local_space);
|
|
|
|
// ---- emit, walking the cells ASCENDING so the tie rule's "first by index" is the walk order itself
|
|
long long w = s_a[t];
|
|
long long e = off_eq;
|
|
for (long long j = lo; j < hi; ++j) {
|
|
const uint32_t k = order_key(scores[j]);
|
|
if (k > thr) out_ids[w++] = (int) j;
|
|
else if (k == thr && e < eq_budget) { ++e; out_ids[w++] = (int) j; }
|
|
}
|
|
}
|
|
|
|
// ================= 5. kv_gather =================
|
|
|
|
__dpct_inline__ void kv_gather_kernel(
|
|
const uint16_t *__restrict__ k_pool, const uint16_t *__restrict__ v_pool,
|
|
const int32_t *__restrict__ table, const int32_t *__restrict__ ids,
|
|
const int32_t *__restrict__ step, int kv_heads, int head_dim, int page_size,
|
|
uint16_t *__restrict__ k_scratch, uint16_t *__restrict__ v_scratch) {
|
|
/*
|
|
DPCT1098: The '*' expression is used instead of the __ldg call. These
|
|
two expressions do not provide the exact same functionality. Check the
|
|
generated code for potential precision and/or performance issues.
|
|
*/
|
|
auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
|
|
const long long n_ids = (long long)*(step + kStepWidth);
|
|
const int per = head_dim / 4; // 4 halfs per uint2
|
|
const long long total = n_ids * kv_heads * per;
|
|
const long long i =
|
|
item_ct1.get_group(2) * (long long)item_ct1.get_local_range(2) +
|
|
item_ct1.get_local_id(2);
|
|
if (i >= total) return;
|
|
const long long id = i / (kv_heads * (long long) per);
|
|
const int rem = (int) (i % (kv_heads * (long long) per));
|
|
const int h = rem / per, q = rem - h * per;
|
|
const int cell = ids[id];
|
|
const long long page = (long long) table[cell / page_size];
|
|
const long long src = ((page * kv_heads + h) * page_size + (cell % page_size)) * (long long) per + q;
|
|
const long long dst = (id * kv_heads + h) * (long long) per + q;
|
|
reinterpret_cast<sycl::uint2 *>(k_scratch)[dst] =
|
|
reinterpret_cast<const sycl::uint2 *>(k_pool)[src];
|
|
reinterpret_cast<sycl::uint2 *>(v_scratch)[dst] =
|
|
reinterpret_cast<const sycl::uint2 *>(v_pool)[src];
|
|
}
|
|
|
|
// ================= 6. qsa_attend =================
|
|
|
|
__dpct_inline__ float warp_max(float v) {
|
|
/*
|
|
DPCT1108: '__shfl_xor_sync' was migrated with the experimental feature
|
|
masked sub_group function which may not be supported by all compilers or
|
|
runtimes. You may need to adjust the code.
|
|
*/
|
|
#pragma unroll
|
|
for (int o = 16; o > 0; o >>= 1) v = sycl::fmax(
|
|
v, dpct::experimental::permute_sub_group_by_xor(
|
|
0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),
|
|
v, o));
|
|
return v;
|
|
}
|
|
|
|
__dpct_inline__ float warp_sum(float v) {
|
|
/*
|
|
DPCT1108: '__shfl_xor_sync' was migrated with the experimental feature
|
|
masked sub_group function which may not be supported by all compilers or
|
|
runtimes. You may need to adjust the code.
|
|
*/
|
|
#pragma unroll
|
|
for (int o = 16; o > 0; o >>= 1) v +=
|
|
dpct::experimental::permute_sub_group_by_xor(
|
|
0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(), v,
|
|
o);
|
|
return v;
|
|
}
|
|
|
|
/// One block per query head. `s` holds the scores, which are then overwritten with the softmax weights.
|
|
/*
|
|
DPCT1110: The total declared local variable size in device function
|
|
qsa_attend_kernel exceeds 128 bytes and may cause high register pressure.
|
|
Consult with your hardware vendor to find the total register size available and
|
|
adjust the code, or use smaller sub-group size to avoid high register pressure.
|
|
*/
|
|
__dpct_inline__ void qsa_attend_kernel(
|
|
const float *__restrict__ q, const uint16_t *__restrict__ k_scratch,
|
|
const uint16_t *__restrict__ v_scratch, const int32_t *__restrict__ step,
|
|
int n_head, int n_head_kv, int head_dim, float *__restrict__ attn,
|
|
float *__restrict__ weights, uint8_t *dpct_local) {
|
|
/*
|
|
DPCT1098: The '*' expression is used instead of the __ldg call. These
|
|
two expressions do not provide the exact same functionality. Check the
|
|
generated code for potential precision and/or performance issues.
|
|
*/
|
|
auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
|
|
const long long n_ids = (long long)*(step + kStepWidth);
|
|
auto s_w = (float *)dpct_local; // CAPACITY floats (scores, then weights) +
|
|
// 32 for the reductions
|
|
float* red = s_w; // red[0..31] live past the scores/weights: see the launch
|
|
float* w = s_w + 32;
|
|
const int h = item_ct1.get_group(2);
|
|
const int d = item_ct1.get_local_id(2);
|
|
// AN EMPTY SELECTION IS HANDLED HERE, not by a host early return. The wrapper used to check `n_ids == 0`
|
|
// and `cudaMemsetAsync` the output, but `n_ids` is a device value now - so the branch has to be on the
|
|
// device, and this is also the only form a graph can replay: the launch is unconditional and the kernel
|
|
// decides. Below the selection bound the selection is the IDENTITY, so `n_ids` is never 0 there; it is
|
|
// reachable only for a genuinely empty cache, and the reference returns zeros for that.
|
|
if (n_ids == 0) {
|
|
#pragma unroll
|
|
for (int i = d; i < head_dim; i += item_ct1.get_local_range(2))
|
|
attn[(size_t)h * head_dim + i] = 0.0f;
|
|
return;
|
|
}
|
|
const int kv = h / (n_head / n_head_kv); // ops.cpp L8729: iv2 = iq2 / rv2, NOT h % n_head_kv
|
|
const float scale = 1.0f / sycl::sqrt((float)head_dim);
|
|
const int lane = d & 31, wid = d >> 5,
|
|
nwarp = (int)((item_ct1.get_local_range(2) + 31) >> 5);
|
|
|
|
for (long long j = d; j < n_ids; j += item_ct1.get_local_range(2)) {
|
|
const uint16_t* krow = k_scratch + (j * n_head_kv + kv) * head_dim;
|
|
float acc = 0.0f;
|
|
#pragma unroll
|
|
for (int i = 0; i < head_dim; ++i) acc +=
|
|
h2f(krow[i]) * q[(size_t)h * head_dim + i];
|
|
w[j] = acc * scale;
|
|
}
|
|
/*
|
|
DPCT1065: Consider replacing sycl::nd_item::barrier() with
|
|
sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
|
|
performance if there is no access to global memory.
|
|
*/
|
|
item_ct1.barrier();
|
|
|
|
float mx = -FLT_MAX; // not -inf, whose double -> float conversion nvcc warns about
|
|
#pragma unroll
|
|
for (long long j = d; j < n_ids; j += item_ct1.get_local_range(2))
|
|
mx = sycl::fmax(mx, w[j]);
|
|
mx = warp_max(mx);
|
|
if (lane == 0) red[wid] = mx;
|
|
/*
|
|
DPCT1065: Consider replacing sycl::nd_item::barrier() with
|
|
sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
|
|
performance if there is no access to global memory.
|
|
*/
|
|
item_ct1.barrier();
|
|
if (wid == 0) {
|
|
mx = (lane < nwarp) ? red[lane] : -FLT_MAX;
|
|
mx = warp_max(mx);
|
|
if (lane == 0) red[0] = mx;
|
|
}
|
|
/*
|
|
DPCT1065: Consider replacing sycl::nd_item::barrier() with
|
|
sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
|
|
performance if there is no access to global memory.
|
|
*/
|
|
item_ct1.barrier();
|
|
mx = red[0];
|
|
/*
|
|
DPCT1065: Consider replacing sycl::nd_item::barrier() with
|
|
sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
|
|
performance if there is no access to global memory.
|
|
*/
|
|
item_ct1.barrier();
|
|
|
|
float sum = 0.0f;
|
|
for (long long j = d; j < n_ids; j += item_ct1.get_local_range(2)) {
|
|
const float e = sycl::native::exp(w[j] - mx);
|
|
w[j] = e;
|
|
sum += e;
|
|
}
|
|
sum = warp_sum(sum);
|
|
if (lane == 0) red[wid] = sum;
|
|
/*
|
|
DPCT1065: Consider replacing sycl::nd_item::barrier() with
|
|
sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
|
|
performance if there is no access to global memory.
|
|
*/
|
|
item_ct1.barrier();
|
|
if (wid == 0) {
|
|
sum = (lane < nwarp) ? red[lane] : 0.0f;
|
|
sum = warp_sum(sum);
|
|
if (lane == 0) red[0] = 1.0f / sum;
|
|
}
|
|
/*
|
|
DPCT1065: Consider replacing sycl::nd_item::barrier() with
|
|
sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
|
|
performance if there is no access to global memory.
|
|
*/
|
|
item_ct1.barrier();
|
|
const float inv = red[0];
|
|
/*
|
|
DPCT1065: Consider replacing sycl::nd_item::barrier() with
|
|
sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
|
|
performance if there is no access to global memory.
|
|
*/
|
|
item_ct1.barrier();
|
|
|
|
float acc = 0.0f;
|
|
#pragma unroll
|
|
for (long long j = 0; j < n_ids; ++j)
|
|
acc += (w[j] * inv) * h2f(v_scratch[(j * n_head_kv + kv) * head_dim + d]);
|
|
attn[(size_t) h * head_dim + d] = acc;
|
|
if (weights != nullptr) {
|
|
#pragma unroll
|
|
for (long long j = d; j < n_ids; j += item_ct1.get_local_range(2))
|
|
weights[(size_t)h * n_ids + j] = w[j] * inv;
|
|
}
|
|
}
|
|
|
|
// ================= 7. qsa_gate_apply =================
|
|
|
|
__dpct_inline__ void qsa_gate_apply_kernel(const float *__restrict__ attn,
|
|
const float *__restrict__ q_full,
|
|
int n_head, int head_dim,
|
|
uint16_t *__restrict__ out) {
|
|
auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
|
|
const long long i =
|
|
item_ct1.get_group(2) * (long long)item_ct1.get_local_range(2) +
|
|
item_ct1.get_local_id(2);
|
|
if (i >= (long long) n_head * head_dim) return;
|
|
const int h = (int) (i / head_dim), d = (int) (i % head_dim);
|
|
const double g = (double) q_full[((size_t) h * 2 * head_dim) + head_dim + d]; // the SECOND half
|
|
const double sig = 1.0 / (1.0 + sycl::exp(-g));
|
|
out[i] = f16_from_f32((float) ((double) attn[i] * sig));
|
|
}
|
|
|
|
inline unsigned grid_for(long long n, int threads) {
|
|
return (unsigned) ((n + threads - 1) / threads);
|
|
}
|
|
|
|
} // namespace
|
|
|
|
/// THE STEP STATE, UPLOADED. Every kernel below reads its per-token counts from here rather than from a kernel
|
|
/// argument, because a CUDA graph bakes arguments in at capture time - see the long note in `qsa.hpp`. This
|
|
/// module-level buffer is what lets the OLD host-scalar signatures keep working unchanged while the kernels
|
|
/// already read the device values; the layer will pass its own buffer once it captures.
|
|
///
|
|
/// It is per-PROCESS and reused, which is safe because the upload and the kernel that reads it are on the same
|
|
/// stream and the host is the only writer. `cudaMemcpyAsync` on the null stream is ordered against the null
|
|
/// stream's kernels, which is what every direct-launch caller here uses.
|
|
namespace {
|
|
|
|
int32_t *step_scratch() try {
|
|
static int32_t* d_step = nullptr;
|
|
if (d_step == nullptr) {
|
|
if (DPCT_CHECK_ERROR(
|
|
d_step = (int32_t *)sycl::malloc_device(
|
|
qsa_step_bytes(), dpct::get_in_order_queue())) != 0) {
|
|
std::fprintf(stderr, "qsa: step upload: cudaMalloc failed\n");
|
|
std::exit(1);
|
|
}
|
|
}
|
|
return d_step;
|
|
}
|
|
catch (sycl::exception const &exc) {
|
|
std::cerr << exc.what() << "Exception caught at file:" << __FILE__
|
|
<< ", line:" << __LINE__ << std::endl;
|
|
std::exit(1);
|
|
}
|
|
|
|
void step_upload_raw(const int32_t *h_step) try {
|
|
int32_t* d = step_scratch();
|
|
/*
|
|
DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming in
|
|
the original code the source host memory is pageable memory. If the memory
|
|
is not pageable, call wait() on event return by memcpy API to ensure
|
|
synchronization behavior.
|
|
*/
|
|
if (DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(
|
|
d, h_step, qsa_step_bytes()).wait()) != 0) {
|
|
std::fprintf(stderr, "qsa: step upload: cudaMemcpy failed\n");
|
|
std::exit(1);
|
|
}
|
|
}
|
|
catch (sycl::exception const &exc) {
|
|
std::cerr << exc.what() << "Exception caught at file:" << __FILE__
|
|
<< ", line:" << __LINE__ << std::endl;
|
|
std::exit(1);
|
|
}
|
|
|
|
/// From a POSITION: fills all four entries. This is the form the layer will use, and the only form that cannot
|
|
/// produce an inconsistent `n_kv`/`n_bid`/`width`.
|
|
const int32_t* step_upload(int64_t pos, int64_t n_kv_hint, const QsaShapes& s) {
|
|
int32_t h[kStepCount];
|
|
qsa_step_fill(h, pos, s);
|
|
// A caller that also knows `n_kv` is CHECKED against it rather than believed: a disagreement is exactly the
|
|
// inconsistency `qsa_step_fill` exists to make impossible, so it is worth an exit rather than a silent
|
|
// preference for one of the two.
|
|
if (n_kv_hint >= 0 && n_kv_hint != (int64_t) h[kStepNKv]) {
|
|
std::fprintf(stderr, "qsa: step upload: n_kv %lld disagrees with pos+1 = %d\n", (long long) n_kv_hint,
|
|
h[kStepNKv]);
|
|
std::exit(1);
|
|
}
|
|
step_upload_raw(h);
|
|
return step_scratch();
|
|
}
|
|
|
|
/// From a WIDTH. `kv_gather` and `qsa_attend` are handed the selection width directly and never see `pos`, so
|
|
/// only that entry is meaningful for them; the others are set consistently anyway rather than left stale,
|
|
/// because a stale entry is a value the NEXT kernel might read.
|
|
const int32_t* step_upload_width(int64_t width, const QsaShapes& s) {
|
|
int32_t h[kStepCount];
|
|
for (int i = 0; i < kStepCount; ++i) h[i] = 0;
|
|
h[kStepWidth] = (int32_t) width;
|
|
(void) s;
|
|
step_upload_raw(h);
|
|
return step_scratch();
|
|
}
|
|
|
|
} // namespace
|
|
|
|
// ================= THE CAPTURABLE ENTRY POINTS =================
|
|
//
|
|
// These are the REAL implementations: every launch below is sized from a constant capacity and every per-token
|
|
// count comes from `step`. The host-scalar entry points further down are wrappers that fill a module-level step
|
|
// buffer and forward this token's counts as the capacities.
|
|
|
|
void kv_append_step(uint16_t* k_pool, uint16_t* v_pool, const int32_t* page_table, const int32_t* step,
|
|
const float* kcur, const float* vcur, const QsaShapes& s, void* stream, const KvHostPools* host) {
|
|
validate(s, "kv_append");
|
|
if (step == nullptr) fail("kv_append: step is null");
|
|
// The grid is the head x dim count, which is a CONSTANT - `kv_append` writes one cell.
|
|
const long long n = s.n_head_kv * s.head_dim;
|
|
{
|
|
auto exp_props = sycl::ext::oneapi::experimental::properties{
|
|
sycl::ext::oneapi::experimental::use_root_sync};
|
|
|
|
strata::q_of(stream)
|
|
->submit([&](sycl::handler &cgh) {
|
|
KvHostPools host_host_KvHostPools_ct9 =
|
|
host ? *host : KvHostPools{};
|
|
|
|
cgh.parallel_for<
|
|
dpct_kernel_name<class kv_append_kernel_19f129>>(
|
|
sycl::nd_range<3>(sycl::range(1, 1, grid_for(n, THREADS)) *
|
|
sycl::range(1, 1, THREADS),
|
|
sycl::range(1, 1, THREADS)),
|
|
exp_props, [=](sycl::nd_item<3> item_ct1) {
|
|
kv_append_kernel(k_pool, v_pool, page_table, step, kcur,
|
|
vcur, (int)s.n_head_kv,
|
|
(int)s.head_dim, (int)s.page_size,
|
|
host_host_KvHostPools_ct9);
|
|
});
|
|
});
|
|
}
|
|
check_launch("kv_append");
|
|
if (stream == nullptr) check_sync("kv_append");
|
|
}
|
|
|
|
void qsa_index_step(const float* pooled, const float* q_idx, const float* bias, const QsaShapes& s,
|
|
const int32_t* step, int64_t max_blocks, float* cell_scores, void* stream) {
|
|
validate(s, "qsa_index");
|
|
if (step == nullptr) fail("qsa_index: step is null");
|
|
if (max_blocks <= 0) fail("qsa_index: max_blocks must be positive");
|
|
// THE GRID IS `max_blocks`, A CONSTANT - not this token's `n_bid + 1`. The kernel returns for
|
|
// `b > n_bid`, so the surplus blocks cost a launch and nothing else.
|
|
const int threads = 32 * (int) s.idx_n_head;
|
|
/*
|
|
DPCT1049: The work-group size passed to the SYCL kernel may exceed the
|
|
limit. To get the device limit, query info::device::max_work_group_size.
|
|
Adjust the work-group size if needed.
|
|
*/
|
|
{
|
|
auto exp_props = sycl::ext::oneapi::experimental::properties{
|
|
sycl::ext::oneapi::experimental::use_root_sync};
|
|
dpct::has_capability_or_fail(
|
|
strata::q_of(stream)->get_device(),
|
|
{sycl::aspect::fp64});
|
|
|
|
strata::q_of(stream)
|
|
->parallel_for<dpct_kernel_name<class qsa_index_kernel_bb65cd>>(
|
|
sycl::nd_range<3>(sycl::range(1, 1, (unsigned)max_blocks) *
|
|
sycl::range(1, 1, threads),
|
|
sycl::range(1, 1, threads)),
|
|
exp_props,
|
|
[=](sycl::nd_item<3> item_ct1)
|
|
[[sycl::reqd_sub_group_size(32)]] {
|
|
qsa_index_kernel(pooled, q_idx, bias, (int)s.idx_n_head,
|
|
(int)s.idx_dim, s.idx_block, step,
|
|
cell_scores);
|
|
});
|
|
}
|
|
check_launch("qsa_index");
|
|
if (stream == nullptr) check_sync("qsa_index");
|
|
}
|
|
|
|
void topk_512_step(const float* cell_scores, const QsaShapes& s, int64_t cap, const int32_t* step,
|
|
int32_t* ids, void* stream) {
|
|
validate(s, "topk_512");
|
|
if (step == nullptr) fail("topk_512: step is null");
|
|
// `cap` is checked against the GEOMETRY'S largest possible width rather than this token's, because this
|
|
// token's is a device value. The two are the same guarantee: `width = min(n_kv, top_k + r - 1)` and
|
|
// `n_kv <= kTopkMaxCells`, so this is the most the kernel can ever write.
|
|
const int64_t width_max = qsa_selection_width(kTopkMaxCells, s);
|
|
if (cap < width_max) {
|
|
std::fprintf(stderr, "qsa: topk_512: cap %lld < the largest possible selection width %lld\n",
|
|
(long long) cap, (long long) width_max);
|
|
std::exit(1);
|
|
}
|
|
// One block, so the launch is already constant; the kernel reads `n_kv` and `width` from `step`.
|
|
{
|
|
auto exp_props = sycl::ext::oneapi::experimental::properties{
|
|
sycl::ext::oneapi::experimental::use_root_sync};
|
|
|
|
strata::q_of(stream)
|
|
->parallel_for<dpct_kernel_name<class topk_kernel_97d5c9>>(
|
|
sycl::nd_range<3>(sycl::range(1, 1, TOPK_THREADS),
|
|
sycl::range(1, 1, TOPK_THREADS)),
|
|
exp_props, [=](sycl::nd_item<3> item_ct1) {
|
|
topk_kernel(cell_scores, step, ids);
|
|
});
|
|
}
|
|
check_launch("topk_512");
|
|
if (stream == nullptr) check_sync("topk_512");
|
|
}
|
|
|
|
void kv_gather_step(const uint16_t* k_pool, const uint16_t* v_pool, const int32_t* page_table,
|
|
const int32_t* ids, const int32_t* step, int64_t max_ids, const QsaShapes& s,
|
|
uint16_t* k_scratch, uint16_t* v_scratch, void* stream) {
|
|
validate(s, "kv_gather");
|
|
if (step == nullptr) fail("kv_gather: step is null");
|
|
if (max_ids <= 0) return;
|
|
// THE GRID IS THE CAPACITY. The kernel reads the real `n_ids` from `step` and its `if (i >= total) return;`
|
|
// guard leaves the surplus threads idle.
|
|
const long long total = max_ids * s.n_head_kv * (s.head_dim / 4);
|
|
{
|
|
auto exp_props = sycl::ext::oneapi::experimental::properties{
|
|
sycl::ext::oneapi::experimental::use_root_sync};
|
|
|
|
strata::q_of(stream)
|
|
->parallel_for<dpct_kernel_name<class kv_gather_kernel_3473e7>>(
|
|
sycl::nd_range<3>(sycl::range(1, 1, grid_for(total, 256)) *
|
|
sycl::range(1, 1, 256),
|
|
sycl::range(1, 1, 256)),
|
|
exp_props, [=](sycl::nd_item<3> item_ct1) {
|
|
kv_gather_kernel(k_pool, v_pool, page_table, ids, step,
|
|
(int)s.n_head_kv, (int)s.head_dim,
|
|
(int)s.page_size, k_scratch, v_scratch);
|
|
});
|
|
}
|
|
check_launch("kv_gather");
|
|
if (stream == nullptr) check_sync("kv_gather");
|
|
}
|
|
|
|
void qsa_attend_step(const float *q, const uint16_t *k_scratch,
|
|
const uint16_t *v_scratch, const int32_t *step,
|
|
int64_t max_ids, const QsaShapes &s, float *attn,
|
|
float *weights, void *stream) try {
|
|
validate(s, "qsa_attend");
|
|
if (step == nullptr) fail("qsa_attend: step is null");
|
|
if (max_ids <= 0) fail("qsa_attend: max_ids must be positive");
|
|
// THE SHARED SIZE IS THE CAPACITY. Shared memory is part of the LAUNCH CONFIGURATION, so sizing it from
|
|
// this token's `n_ids` bakes the sequence length in: a captured layer would allocate room for token 1 and
|
|
// then index past it at token 500. The kernel reads the real count from `step`, so a larger allocation is
|
|
// exactly what it wants. The opt-in therefore happens once, for the capacity.
|
|
/*
|
|
DPCT1083: The size of local memory in the migrated code may be different
|
|
from the original code. Check that the allocated memory size in the migrated
|
|
code is correct.
|
|
*/
|
|
const size_t smem = (size_t)(max_ids + 32) * sizeof(float);
|
|
// per DEVICE: the opt-in is a device setting (a layer split runs this on two cards)
|
|
static size_t s_configured_dev[64] = {};
|
|
int cur_dev = 0;
|
|
cur_dev = dpct::get_current_device_id();
|
|
size_t& s_configured = s_configured_dev[(cur_dev >= 0 && cur_dev < 64) ? cur_dev : 0];
|
|
if (smem > s_configured) {
|
|
int dev = 0, max_shared = 0;
|
|
dev = dpct::get_current_device_id();
|
|
/*
|
|
DPCT1019: local_mem_size in SYCL is not a complete equivalent of
|
|
cudaDevAttrMaxSharedMemoryPerBlockOptin in CUDA. You may need to adjust
|
|
the code.
|
|
*/
|
|
max_shared = dpct::get_device(dev).get_local_mem_size();
|
|
max_shared = strata::smem_optin_of(max_shared);
|
|
if ((int) smem > max_shared) {
|
|
std::fprintf(stderr, "qsa: qsa_attend: max_ids %lld needs %zu B of shared, over the %d B limit\n",
|
|
(long long) max_ids, smem, max_shared);
|
|
std::exit(1);
|
|
}
|
|
const dpct::err0 e =
|
|
/*
|
|
DPCT1027: The call to cudaFuncSetAttribute was replaced with 0
|
|
because SYCL currently does not support corresponding setting.
|
|
*/
|
|
0;
|
|
|
|
s_configured = smem;
|
|
}
|
|
/*
|
|
DPCT1049: The work-group size passed to the SYCL kernel may exceed the
|
|
limit. To get the device limit, query info::device::max_work_group_size.
|
|
Adjust the work-group size if needed.
|
|
*/
|
|
{
|
|
auto exp_props = sycl::ext::oneapi::experimental::properties{
|
|
sycl::ext::oneapi::experimental::use_root_sync};
|
|
|
|
strata::q_of(stream)
|
|
->submit([&](sycl::handler &cgh) {
|
|
sycl::local_accessor<uint8_t, 1> dpct_local_acc_ct1(
|
|
sycl::range(smem), cgh);
|
|
|
|
cgh.parallel_for<
|
|
dpct_kernel_name<class qsa_attend_kernel_6a355d>>(
|
|
sycl::nd_range<3>(
|
|
sycl::range(1, 1, (unsigned)s.n_head) *
|
|
sycl::range(1, 1, (unsigned)s.head_dim),
|
|
sycl::range(1, 1, (unsigned)s.head_dim)),
|
|
exp_props,
|
|
[=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(
|
|
32)]] {
|
|
qsa_attend_kernel(
|
|
q, k_scratch, v_scratch, step, (int)s.n_head,
|
|
(int)s.n_head_kv, (int)s.head_dim, attn, weights,
|
|
dpct_local_acc_ct1
|
|
.get_multi_ptr<sycl::access::decorated::no>()
|
|
.get());
|
|
});
|
|
});
|
|
}
|
|
check_launch("qsa_attend");
|
|
if (stream == nullptr) check_sync("qsa_attend");
|
|
}
|
|
catch (sycl::exception const &exc) {
|
|
std::cerr << exc.what() << "Exception caught at file:" << __FILE__
|
|
<< ", line:" << __LINE__ << std::endl;
|
|
std::exit(1);
|
|
}
|
|
|
|
// ================= host entry points =================
|
|
|
|
void qsa_step_fill(int32_t* host_step, int64_t pos, const QsaShapes& s) {
|
|
if (host_step == nullptr) return;
|
|
if (pos < 0) fail("qsa_step_fill: pos < 0");
|
|
// ONE PLACE COMPUTES ALL FOUR, which is the whole reason the step state is a BUFFER rather than four
|
|
// separate parameters. `n_kv`, `n_bid` and `width` are DERIVED from `pos`, so a caller filling them in
|
|
// itself could fill them inconsistently - and `qsa_index`'s host guard against exactly that inconsistency
|
|
// now has a single writer to check against instead of two independent arguments.
|
|
//
|
|
// This is the form the LAYER will use: every value a QSA kernel needs derives from one position, so one
|
|
// H2D per token updates all of them and no entry point takes a per-token scalar.
|
|
const int64_t n_kv = pos + 1;
|
|
host_step[kStepPos] = (int32_t) pos;
|
|
host_step[kStepNKv] = (int32_t) n_kv;
|
|
host_step[kStepNBid] = (int32_t) (n_kv / s.idx_block);
|
|
host_step[kStepWidth] = (int32_t) qsa_selection_width(n_kv, s);
|
|
}
|
|
|
|
void kv_append(uint16_t* k_pool, uint16_t* v_pool, const int32_t* page_table, int64_t pos,
|
|
const float* kcur, const float* vcur, const QsaShapes& s, void* stream) {
|
|
if (pos < 0) { validate(s, "kv_append"); fail("kv_append: pos < 0"); }
|
|
kv_append_step(k_pool, v_pool, page_table, step_upload(pos, -1, s), kcur, vcur, s, stream);
|
|
}
|
|
|
|
void indexer_key_append(const float* raw, const int32_t* pos_dev, int32_t pos_base, const float* w_k_norm,
|
|
float eps, const QsaIndexerBuffers& b, const QsaShapes& s, const float* cos_tab,
|
|
const float* sin_tab, void* stream) {
|
|
validate(s, "indexer_key_append");
|
|
if (pos_dev == nullptr) fail("indexer_key_append: pos_dev is null");
|
|
if (b.tail == nullptr || b.dead == nullptr || b.pooled == nullptr || b.block_pos == nullptr)
|
|
fail("indexer_key_append: the indexer buffers are not all set (tail/dead/pooled/block_pos)");
|
|
const int threads = (int) s.idx_dim;
|
|
/*
|
|
DPCT1083: The size of local memory in the migrated code may be different
|
|
from the original code. Check that the allocated memory size in the migrated
|
|
code is correct.
|
|
*/
|
|
const size_t smem = (size_t)s.idx_dim * sizeof(double);
|
|
// **ONE LAUNCH, NO HOST BRANCH ON THE POSITION.** The completion rotation is inside the kernel now. The
|
|
// arguments here are identical for every token, which is the property a CUDA graph needs: this function can
|
|
// be captured and replayed, and the position arrives through `pos_dev` like every other kernel's data.
|
|
/*
|
|
DPCT1049: The work-group size passed to the SYCL kernel may exceed the
|
|
limit. To get the device limit, query info::device::max_work_group_size.
|
|
Adjust the work-group size if needed.
|
|
*/
|
|
{
|
|
auto exp_props = sycl::ext::oneapi::experimental::properties{
|
|
sycl::ext::oneapi::experimental::use_root_sync};
|
|
dpct::has_capability_or_fail(
|
|
strata::q_of(stream)->get_device(),
|
|
{sycl::aspect::fp64});
|
|
|
|
strata::q_of(stream)
|
|
->submit([&](sycl::handler &cgh) {
|
|
sycl::local_accessor<uint8_t, 1> dpct_local_acc_ct1(
|
|
sycl::range(smem), cgh);
|
|
|
|
auto mrope_table_ct14 = mrope_table();
|
|
|
|
cgh.parallel_for<
|
|
dpct_kernel_name<class indexer_key_append_kernel_9e74e0>>(
|
|
sycl::nd_range<3>(sycl::range(1, 1, threads),
|
|
sycl::range(1, 1, threads)),
|
|
exp_props, [=](sycl::nd_item<3> item_ct1) {
|
|
indexer_key_append_kernel(
|
|
raw, pos_dev, (int)pos_base, w_k_norm, eps, b.tail,
|
|
b.dead, b.pooled, b.block_pos, (int)s.idx_dim,
|
|
(int)s.idx_block, (int)s.n_rot, cos_tab, sin_tab,
|
|
mrope_table_ct14,
|
|
dpct_local_acc_ct1
|
|
.get_multi_ptr<sycl::access::decorated::no>()
|
|
.get());
|
|
});
|
|
});
|
|
}
|
|
check_launch("indexer_key_append");
|
|
if (stream == nullptr) check_sync("indexer_key_append");
|
|
}
|
|
|
|
void qsa_index(const float* pooled, int64_t n_bid, const float* q_idx, const float* bias, const QsaShapes& s,
|
|
int64_t n_kv, float* cell_scores, void* stream) {
|
|
validate(s, "qsa_index");
|
|
if (n_bid < 0 || n_kv <= 0) fail("qsa_index: n_bid < 0 or n_kv <= 0");
|
|
// `n_kv`, `n_bid` and `width` are DERIVED from one position, so this refuses a caller whose two arguments
|
|
// disagree rather than launching a kernel that would score the wrong number of blocks.
|
|
if ((n_kv / s.idx_block) != n_bid) {
|
|
std::fprintf(stderr, "qsa: qsa_index: n_bid %lld is not n_kv %lld / r %lld\n", (long long) n_bid,
|
|
(long long) n_kv, (long long) s.idx_block);
|
|
std::exit(1);
|
|
}
|
|
// THIS TOKEN'S counts as the CAPACITIES: correct for a direct launch, WRONG in a graph. The layer passes a
|
|
// constant `max_blocks` from its state instead - see the note in `qsa.hpp`.
|
|
qsa_index_step(pooled, q_idx, bias, s, step_upload(n_kv - 1, n_kv, s), n_bid + 1, cell_scores, stream);
|
|
}
|
|
|
|
void topk_512(const float* cell_scores, int64_t n_kv, const QsaShapes& s, int64_t cap, int32_t* ids,
|
|
void* stream) {
|
|
validate(s, "topk_512");
|
|
if (n_kv <= 0) return;
|
|
if (n_kv > kTopkMaxCells) {
|
|
std::fprintf(stderr, "qsa: topk_512: n_kv %lld > kTopkMaxCells %lld (one block; phase 3 replaces this)\n",
|
|
(long long) n_kv, (long long) kTopkMaxCells);
|
|
std::exit(1);
|
|
}
|
|
topk_512_step(cell_scores, s, cap, step_upload(n_kv - 1, n_kv, s), ids, stream);
|
|
}
|
|
|
|
void kv_gather(const uint16_t* k_pool, const uint16_t* v_pool, const int32_t* page_table, const int32_t* ids,
|
|
int64_t n_ids, const QsaShapes& s, uint16_t* k_scratch, uint16_t* v_scratch, void* stream) {
|
|
validate(s, "kv_gather");
|
|
if (n_ids <= 0) return;
|
|
kv_gather_step(k_pool, v_pool, page_table, ids, step_upload_width(n_ids, s), n_ids, s, k_scratch,
|
|
v_scratch, stream);
|
|
}
|
|
|
|
void qsa_attend(const float* q, const uint16_t* k_scratch, const uint16_t* v_scratch, int64_t n_ids,
|
|
const QsaShapes& s, float* attn, float* weights, void* stream) {
|
|
validate(s, "qsa_attend");
|
|
if (n_ids < 0) fail("qsa_attend: n_ids < 0");
|
|
if (n_ids == 0) {
|
|
// The empty selection goes through the kernel's own zero path; `max_ids` must still be positive, so the
|
|
// wrapper gives it the geometry's capacity rather than 0.
|
|
qsa_attend_step(q, k_scratch, v_scratch, step_upload_width(0, s),
|
|
qsa_selection_width(kTopkMaxCells, s), s, attn, weights, stream);
|
|
return;
|
|
}
|
|
qsa_attend_step(q, k_scratch, v_scratch, step_upload_width(n_ids, s), n_ids, s, attn, weights, stream);
|
|
}
|
|
|
|
/// The same multiply as `qsa_gate_apply_kernel` WITHOUT the fp16 round - see the header for why the caller
|
|
/// whose weight is a K-quant needs the f32 form. Identical arithmetic up to the last step.
|
|
__dpct_inline__ void qsa_gate_apply_f32_kernel(const float *__restrict__ attn,
|
|
const float *__restrict__ q_full,
|
|
int n_head, int head_dim,
|
|
float *__restrict__ out) {
|
|
auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
|
|
const long long i =
|
|
item_ct1.get_group(2) * (long long)item_ct1.get_local_range(2) +
|
|
item_ct1.get_local_id(2);
|
|
if (i >= (long long) n_head * head_dim) return;
|
|
const int h = (int) (i / head_dim), d = (int) (i % head_dim);
|
|
const double g = (double) q_full[((size_t) h * 2 * head_dim) + head_dim + d]; // the SECOND half
|
|
const double sig = 1.0 / (1.0 + sycl::exp(-g));
|
|
out[i] = (float) ((double) attn[i] * sig);
|
|
}
|
|
|
|
void qsa_gate_apply_f32(const float* attn, const float* q_full, const QsaShapes& s, float* out, void* stream) {
|
|
validate(s, "qsa_gate_apply_f32");
|
|
const long long n = s.n_head * s.head_dim;
|
|
{
|
|
auto exp_props = sycl::ext::oneapi::experimental::properties{
|
|
sycl::ext::oneapi::experimental::use_root_sync};
|
|
dpct::has_capability_or_fail(
|
|
strata::q_of(stream)->get_device(),
|
|
{sycl::aspect::fp64});
|
|
|
|
strata::q_of(stream)
|
|
->parallel_for<
|
|
dpct_kernel_name<class qsa_gate_apply_f32_kernel_7cff4f>>(
|
|
sycl::nd_range<3>(sycl::range(1, 1, grid_for(n, 256)) *
|
|
sycl::range(1, 1, 256),
|
|
sycl::range(1, 1, 256)),
|
|
exp_props, [=](sycl::nd_item<3> item_ct1) {
|
|
qsa_gate_apply_f32_kernel(attn, q_full, (int)s.n_head,
|
|
(int)s.head_dim, out);
|
|
});
|
|
}
|
|
check_launch("qsa_gate_apply_f32");
|
|
if (stream == nullptr) check_sync("qsa_gate_apply_f32");
|
|
}
|
|
|
|
void qsa_gate_apply(const float* attn, const float* q_full, const QsaShapes& s, uint16_t* out, void* stream) {
|
|
validate(s, "qsa_gate_apply");
|
|
const long long n = s.n_head * s.head_dim;
|
|
{
|
|
auto exp_props = sycl::ext::oneapi::experimental::properties{
|
|
sycl::ext::oneapi::experimental::use_root_sync};
|
|
dpct::has_capability_or_fail(
|
|
strata::q_of(stream)->get_device(),
|
|
{sycl::aspect::fp64});
|
|
|
|
strata::q_of(stream)
|
|
->parallel_for<
|
|
dpct_kernel_name<class qsa_gate_apply_kernel_650dec>>(
|
|
sycl::nd_range<3>(sycl::range(1, 1, grid_for(n, 256)) *
|
|
sycl::range(1, 1, 256),
|
|
sycl::range(1, 1, 256)),
|
|
exp_props, [=](sycl::nd_item<3> item_ct1) {
|
|
qsa_gate_apply_kernel(attn, q_full, (int)s.n_head,
|
|
(int)s.head_dim, out);
|
|
});
|
|
}
|
|
check_launch("qsa_gate_apply");
|
|
if (stream == nullptr) check_sync("qsa_gate_apply");
|
|
}
|
|
|
|
} // namespace strata::kernels
|