okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-q4-sycl (41717f29c): the Intel Arc (SYCL) engine follows the compiled geometry, so q4_lite/q4_mid/q4_big build; default build unchanged (CUDA SASS 3573/3573, HIP gfx1201 3920/3920, gfx1151 string offsets only, Metal 85/85 objects, SYCL 22/22 checksums); A750 gate 2 q4_lite 0.00021 vs floor 0.00017; one conflict with f-clean-6-0 in sycl/src/prefill/prefill.cpp resolved as tested by Q4-SYMERGE (Qwen4 prep)db137d917

main
34.7 KiB711 linesraw
1// src/kernels/cuda/ple.cu - P2.S4: the PLE block's GPU half.
2//
3// See include/strata/kernels/ple.hpp for the structure and for the `normalized`-is-the-conv-input finding.
4//
5// The legacy arithmetic below follows the captured CPU ggml graph
6// (`bench/micro/ple_in.bin` / `ple_out.bin`, produced by `ple_layer_xcheck.cpp`):
7//
8//   * `rms_norm` accumulates `(double)(x*x)` with the PRODUCT rounded in f32 first - that is literally what
9//     `ggml_compute_forward_rms_norm_f32` does (`sum += (ggml_float)(x[i00]*x[i00])` with `ggml_float` =
10//     double), and it is not the same as accumulating in f32 or as widening before the multiply.
11//   * `silu` is `x / (1 + expf(-x))` in f32, which is `ggml_silu_f32`.
12//   * the gate's `sqrt` and `sigmoid` are f32.
13//
14// The opt-in native BF16 path replaces only ple_value with the pinned CUDA single-token BF16/F32 MMVF.
15// A separate opt-in native postops path follows the pinned CUDA arithmetic after both projections.
16#define DPCT_PROFILING_ENABLED
17#include <sycl/sycl.hpp>
18#include "strata/kprof.hpp"
19#include <dpct/dpct.hpp>
20#include "strata/sycl_queue.hpp"
21#include "strata/kernels/ple.hpp"
22#include "strata/kernels/bf16_gemv.hpp"
23#include "strata/kernels/f16_bits.hpp"
24#include "strata/kernels/ngram.hpp"
25#include "strata/kernels/quantize_act.hpp"
26#include "strata/kernels/s2_gemv_q8.hpp"
27#include "strata/kernels/native_mmvq.hpp"
28#include "strata/kernels/native_ple_postops.hpp"
29
30#include <cmath>
31#include <cstdio>
32#include <cstdlib>
33#include <stdexcept>
34#include <string>
35
36namespace strata::kernels {
37namespace {
38
39constexpr int THREADS = 256;
40bool native_bf16 = false;
41bool native_postops = false;
42
43bool overlap(const void* a, size_t a_bytes, const void* b, size_t b_bytes) {
44    if (a == nullptr || b == nullptr || a_bytes == 0 || b_bytes == 0) return false;
45    const uintptr_t aa = reinterpret_cast<uintptr_t>(a), bb = reinterpret_cast<uintptr_t>(b);
46    return aa < bb ? bb - aa < a_bytes : aa - bb < b_bytes;
47}
48
49__dpct_inline__ void
50history_advance_kernel(float *__restrict__ history,
51                       const float *__restrict__ normalized) {
52    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
53    const int channel = item_ct1.get_group(2) * item_ct1.get_local_range(2) +
54                        item_ct1.get_local_id(2);
55    if (channel >= NG_HC_DIM) return;
56    float* column = history + (size_t) channel * NG_HIST;
57#pragma unroll
58    for (int row = 0; row + 1 < NG_HIST; ++row) column[row] = column[row + 1];
59    column[NG_HIST - 1] = normalized[channel];
60}
61
62__dpct_inline__ uint16_t bf16_bits(float f) {
63    uint32_t i;
64    memcpy(&i, &f, 4);
65    i = (i + ((i >> 16) & 1u) + 0x7FFFu) & 0xFFFF0000u;
66    return (uint16_t) (i >> 16);
67}
68
69__dpct_inline__ float bf16_float(uint16_t h) {
70    const uint32_t i = (uint32_t) h << 16;
71    float f;
72    memcpy(&f, &i, 4);
73    return f;
74}
75
76__dpct_inline__ float silu_f(float x) {
77    return x / (1.0f + sycl::native::exp(-x));
78}
79
80/// Block-wide sum in double, broadcast to all threads.  The leading `__syncthreads` matters: the result is
81/// read out of `scratch[0]` and a later call reuses the array, so without a barrier a fast thread can
82/// overwrite it before a slow one has read it - invisible in most runs and a slightly different norm when it
83/// fires.
84inline double block_sum(double v, double *scratch) {
85    /*
86    DPCT1065: Consider replacing sycl::nd_item::barrier() with
87    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
88    performance if there is no access to global memory.
89    */
90    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
91    item_ct1.barrier();
92    const int lane = item_ct1.get_local_id(2) & 31,
93              warp = item_ct1.get_local_id(2) >> 5;
94    /*
95DPCT1108: '__shfl_down_sync' was migrated with the experimental feature
96masked sub_group function which may not be supported by all compilers or
97runtimes. You may need to adjust the code.
98*/
99    /*
100DPCT1121: Make sure that the "v" which is used in the SYCL group
101function/algorithm is initialized.
102*/
103#pragma unroll
104    for (int off = 16; off > 0; off >>= 1) v +=
105        dpct::experimental::shift_sub_group_left(
106            0xFFFFFFFFu, sycl::ext::oneapi::this_work_item::get_sub_group(), v,
107            off);
108    if (lane == 0) scratch[warp] = v;
109    /*
110    DPCT1065: Consider replacing sycl::nd_item::barrier() with
111    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
112    performance if there is no access to global memory.
113    */
114    item_ct1.barrier();
115    const int nw = ((int)item_ct1.get_local_range(2) + 31) >> 5;
116    v = (item_ct1.get_local_id(2) < nw) ? scratch[item_ct1.get_local_id(2)]
117                                        : 0.0;
118    if (warp == 0)
119        /*
120DPCT1108: '__shfl_down_sync' was migrated with the experimental feature
121masked sub_group function which may not be supported by all compilers or
122runtimes. You may need to adjust the code.
123*/
124        /*
125DPCT1121: Make sure that the "v" which is used in the SYCL group
126function/algorithm is initialized.
127*/
128#pragma unroll
129        for (int off = 16; off > 0; off >>= 1) v +=
130            dpct::experimental::shift_sub_group_left(
131                0xFFFFFFFFu, sycl::ext::oneapi::this_work_item::get_sub_group(),
132                v, off);
133    if (item_ct1.get_local_id(2) == 0) scratch[0] = v;
134    /*
135    DPCT1065: Consider replacing sycl::nd_item::barrier() with
136    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
137    performance if there is no access to global memory.
138    */
139    item_ct1.barrier();
140    return scratch[0];
141}
142
143/// `grouped_norm`, ONE BLOCK PER STREAM.  The ggml form is `reshape_3d(x, n_embd, hc, T)` then
144/// `rms_norm(..., eps) * w`, so ne0 = n_embd is the reduction axis and each hc stream is normalised on its
145/// own.  In the flat ggml layout (ne0 fastest) stream c occupies [c*n_embd, (c+1)*n_embd).
146__dpct_inline__ void gnorm_kernel(const float *__restrict__ x,
147                                  const float *__restrict__ w,
148                                  float *__restrict__ y, int n_embd,
149                                  float eps) {
150    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
151auto &scratch = *sycl::ext::oneapi::group_local_memory_for_overwrite<double[8]>(
152    sycl::ext::oneapi::this_work_item::get_work_group<3>());
153    const int c = item_ct1.get_group(2);
154    const float* xc = x + (size_t) c * n_embd;
155    const float* wc = w + (size_t) c * n_embd;
156    float* yc = y + (size_t) c * n_embd;
157
158    double acc = 0.0;
159    for (int d = item_ct1.get_local_id(2); d < n_embd;
160         d += item_ct1.get_local_range(2)) {
161        // The PRODUCT is rounded in f32 before it is widened - `(ggml_float)(x[i00]*x[i00])`.
162        const float sq = xc[d] * xc[d];
163        acc += (double) sq;
164    }
165    const float mean = (float) (block_sum(acc, scratch) / (double) n_embd);
166    const float scale = 1.0f / sycl::sqrt(mean + eps);
167#pragma unroll
168    for (int d = item_ct1.get_local_id(2); d < n_embd;
169         d += item_ct1.get_local_range(2)) yc[d] = xc[d] * scale * wc[d];
170}
171
172/// `s[c] = sum_d key[c][d]*query[c][d] / sqrt(n_embd)`, then the signed square root and the sigmoid.
173///
174/// `mag = sqrt(clamp(|s|, 1e-6, inf))` and `gate = sigmoid(sgn(s) * mag)`.  The clamp is a floor on |s|, so
175/// it only bites near zero; the SIGN is carried separately, which is what keeps the gate symmetric about 0.5.
176__dpct_inline__ void gate_kernel(const float *__restrict__ key,
177                                 const float *__restrict__ query,
178                                 float *__restrict__ gate, int n_embd,
179                                 float inv_sqrt_n) {
180    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
181auto &scratch = *sycl::ext::oneapi::group_local_memory_for_overwrite<double[8]>(
182    sycl::ext::oneapi::this_work_item::get_work_group<3>());
183    const int c = item_ct1.get_group(2);
184    const float* kc = key + (size_t) c * n_embd;
185    const float* qc = query + (size_t) c * n_embd;
186    double acc = 0.0;
187#pragma unroll
188    for (int d = item_ct1.get_local_id(2); d < n_embd;
189         d += item_ct1.get_local_range(2)) acc += (double)(kc[d] * qc[d]);
190    const float s = (float) (block_sum(acc, scratch) / (double) 1.0) * inv_sqrt_n;
191    const float mag = sycl::sqrt(sycl::fmax(sycl::fabs(s), 1e-6f));
192    const float sgn = (s > 0.0f) ? 1.0f : ((s < 0.0f) ? -1.0f : 0.0f);
193    if (item_ct1.get_local_id(2) == 0) gate[c] =
194        1.0f / (1.0f + sycl::native::exp(-(sgn * mag)));
195}
196
197/// `gated[c][d] = value[d] * gate[c]` - the value broadcast across the hc streams.
198__dpct_inline__ void bcast_kernel(const float *__restrict__ value,
199                                  const float *__restrict__ gate,
200                                  float *__restrict__ gated, int n_embd,
201                                  int hc) {
202    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
203    const int i = item_ct1.get_group(2) * item_ct1.get_local_range(2) +
204                  item_ct1.get_local_id(2);
205    if (i >= n_embd * hc) return;
206    gated[i] = value[i % n_embd] * gate[i / n_embd];
207}
208
209/// The depthwise causal dilated conv, then SiLU.  One thread per channel.
210///
211/// `out[c] = sum_k kW[k][c] * terms[t - (kern-1-k)*dil][c]` with `t = hist` (the first new position), so tap k
212/// reads row `hist - (kern-1-k)*dil` of `[history | new]`.  For the real geometry (kern 4, dil 3, hist 9) the
213/// four taps read rows 0, 3, 6 and 9 - and row 9 is the NEW row, which is the only one beyond the history.
214/// That is why no `terms` buffer is built: three taps come from the caller's history and one from `norm`.
215///
216/// `kW` IS GGML-NATIVE: `kW[k + kern*c]`.  The manifest's shape is [4, 10240] with ne0 = 4 fast, and
217/// `ref/ngram.py`'s (4, 10240) numpy `kernel[k][c]` is the TRANSPOSE of that.  The source's own view
218/// (`ggml_view_2d(model.layers[il].ple_conv1d, 1, hc_dim, nb[1], k*nb[0])`) settles which one is meant.
219__dpct_inline__ void conv_kernel(const float *__restrict__ hist,
220                                 const float *__restrict__ norm,
221                                 const uint16_t *__restrict__ kW,
222                                 float *__restrict__ out, int hc_dim, int kern,
223                                 int dil, int nhist) {
224    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
225    const int c = item_ct1.get_group(2) * item_ct1.get_local_range(2) +
226                  item_ct1.get_local_id(2);
227    if (c >= hc_dim) return;
228    float acc = 0.0f;
229    for (int k = 0; k < kern; ++k) {
230        const int row = nhist - (kern - 1 - k) * dil;      // tap 0 reads the FURTHEST back
231        // ROW-FASTEST: `hist[row + nhist*c]`.  The conv state is `ggml_reshape_3d(state, d_conv-1,
232        // conv_channels, n_seqs)`, so ne0 = hist varies fastest and the flat index is row + hist*channel.
233        // Channel-slowest (`row*hc_dim + c`) is the natural thing to write and would read a transposed state -
234        // `ple_layer_xcheck.cpp` L79-83 records getting this wrong once already.
235        const float v = (row == nhist) ? norm[c] : hist[(size_t) row + (size_t) nhist * c];
236        acc += f32_from_f16(kW[k + kern * c]) * v;
237    }
238    out[c] = silu_f(acc);
239}
240
241/// `result = hidden + gated + conv`, elementwise over hc_dim.
242__dpct_inline__ void add3_kernel(const float *__restrict__ hidden,
243                                 const float *__restrict__ gated,
244                                 const float *__restrict__ conv,
245                                 float *__restrict__ result, int n) {
246    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
247    const int i = item_ct1.get_group(2) * item_ct1.get_local_range(2) +
248                  item_ct1.get_local_id(2);
249    if (i < n) result[i] = hidden[i] + gated[i] + conv[i];
250}
251
252/// `y[o] = sum_i bf16(x[i]) * bf16(w[o*n_in + i])`.  The weight is BF16 and so is the ACTIVATION, which is
253/// the contract for a BF16 tensor (`docs/activation-contract.md`); with both sides bf16 the products are
254/// exact in f32 and only the summation order differs from ggml's.
255__dpct_inline__ void bf16_gemv_kernel(const uint16_t *__restrict__ x,
256                                      const uint16_t *__restrict__ w,
257                                      float *__restrict__ y, int n_in,
258                                      int n_out) {
259    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
260    const int o = item_ct1.get_group(2) * item_ct1.get_local_range(2) +
261                  item_ct1.get_local_id(2);
262    if (o >= n_out) return;
263    const uint16_t* row = w + (size_t) o * n_in;
264    double acc = 0.0;
265#pragma unroll
266    for (int i = 0; i < n_in; ++i) acc +=
267        (double)bf16_float(x[i]) * (double)bf16_float(row[i]);
268    y[o] = (float) acc;
269}
270
271__dpct_inline__ void to_bf16_kernel(const float *__restrict__ x,
272                                    uint16_t *__restrict__ y, int n) {
273    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
274    const int i = item_ct1.get_group(2) * item_ct1.get_local_range(2) +
275                  item_ct1.get_local_id(2);
276    if (i < n) y[i] = bf16_bits(x[i]);
277}
278
279void ck(dpct::err0 e, const char *what) {
280}
281
282}  // namespace
283
284void ple_set_native_bf16(bool enabled) { native_bf16 = enabled; }
285bool ple_native_bf16_enabled() { return native_bf16; }
286void ple_set_native_postops(bool enabled) { native_postops = enabled; }
287bool ple_native_postops_enabled() { return native_postops; }
288
289void ple_history_advance(float* hist, const float* normalized, void* stream) {
290    if (hist == nullptr || normalized == nullptr)
291        throw std::invalid_argument("ple_history_advance: null history or normalized input");
292    if (overlap(hist, (size_t) NG_HIST * NG_HC_DIM * sizeof(float),
293                normalized, (size_t) NG_HC_DIM * sizeof(float)))
294        throw std::invalid_argument("ple_history_advance: history and normalized input overlap");
295    {
296        auto exp_props = sycl::ext::oneapi::experimental::properties{
297            sycl::ext::oneapi::experimental::use_root_sync};
298
299        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
300            ->template parallel_for<
301                dpct_kernel_name<class history_advance_kernel_204159>>(
302                sycl::nd_range<3>(
303                    sycl::range(1, 1, (NG_HC_DIM + THREADS - 1) / THREADS) *
304                        sycl::range(1, 1, THREADS),
305                    sycl::range(1, 1, THREADS)),
306                exp_props, [=](sycl::nd_item<3> item_ct1) {
307                    history_advance_kernel(hist, normalized);
308                });
309    }
310    /*
311    DPCT1010: SYCL uses exceptions to report errors and does not use the
312    error codes. The cudaGetLastError function call was replaced with 0. You
313    need to rewrite this code.
314    */
315    ck(0, "history advance launch");
316}
317
318bool ple_block_available() try {
319    int n = 0;
320    return DPCT_CHECK_ERROR(n = dpct::device_count()) == 0 && n > 0;
321}
322catch (sycl::exception const &exc) {
323  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
324            << ", line:" << __LINE__ << std::endl;
325  std::exit(1);
326}
327
328uint64_t ple_block_scratch_bytes() {
329    // five hc_dim floats + n_embd + hc, then the Q8 activation image, then the BF16 embedding copy, each
330    // 16-byte aligned because `d_scratch` is cast to `float*` and `d_act` to `uint8_t*` at those offsets.
331    const size_t f = (size_t) (5 * NG_HC_DIM + NG_N_EMBD + NG_HC) * sizeof(float);
332    const size_t q = (size_t) (NG_N_EMBD / 32) * 34;
333    const size_t e = (size_t) NG_N_EMBD * sizeof(uint16_t);
334    return ((f + 15) & ~(size_t) 15) + ((q + 15) & ~(size_t) 15) + e + 256;
335}
336
337void ple_block(const float* emb, const float* hidden, const float* hist_rows, const PleWeights& w,
338               PleOut& out, void* scratch, void* stream) {
339    const bool native_key = w.key_native_data != nullptr && w.key_bf16 == nullptr;
340    if (native_key && (!emb || !hidden || !hist_rows || !out.result || !scratch || !stream ||
341                       !w.key_native_q8_1 ||
342                       (w.key_native_type != 42 && w.key_native_type != 18 && w.key_native_type != 23 &&
343                        w.key_native_type != 8)))
344        throw std::invalid_argument("ple_block: native key requires Q2_0, IQ3_XXS, IQ4_XS or Q8_0 weights, input/output, private scratch and explicit stream");
345    if (emb == nullptr || hidden == nullptr || hist_rows == nullptr || out.result == nullptr) return;
346    const int n_embd = NG_N_EMBD, hc = NG_HC, hc_dim = NG_HC_DIM;
347    static_assert(NG_N_EMBD % 32 == 0 && NG_HC_DIM == NG_HC * NG_N_EMBD, "native PLE key geometry changed");
348    const size_t float_bytes = (size_t) (5 * hc_dim + n_embd + hc) * sizeof(float);
349    dpct::queue_ptr st = strata::q_of(stream);
350
351    // One allocation for every intermediate.
352    //
353    // THE ENGINE WILL NOT DO THIS.  P2.T10 requires zero token-path allocations, and the fix is the same one
354    // `gr_read` already uses: a caller-owned workspace carved once at startup.  It is done this way here
355    // because this function's job in P2.S4 is to be CORRECT and comparable against the oracle, and matching
356    // `shared_expert.cu`'s existing shape keeps the diff small.  Recorded rather than hidden.
357    //
358    // FIVE SEPARATE hc_dim BUFFERS, deliberately.  `key` and `normalized` are both needed at the end for the
359    // oracle comparison, so aliasing one onto the other - which the first version did - silently returns the
360    // WRONG `key`.  Two buffers of the same size look like an obvious saving and the only thing it saves is
361    // 40 KB.
362    // **THE WORKSPACE IS CARVED FROM THE CALLER'S, NOT ALLOCATED.**  Three `cudaMalloc`s and a
363    // `cudaStreamSynchronize` used to live here, and inside a stream capture both are errors: the engine
364    // reported `ple_block: scratch: operation not permitted when stream is capturing`, and a token-path
365    // allocation is a P2.T10 violation besides.  The comment this replaces already said the right shape was
366    // "a caller-owned workspace carved once at startup"; this is that.
367    const size_t q8_bytes = (size_t) (n_embd / 32) * 34;
368    if (scratch == nullptr) {
369        std::fprintf(stderr, "ple_block: scratch is null; the caller owns it (see ple_block_scratch_bytes)\n");
370        std::exit(1);
371    }
372    const struct Export { const float* pointer; size_t count; const char* name; } exports[] = {
373        {out.key, (size_t) hc_dim, "key"}, {out.value, (size_t) n_embd, "value"},
374        {out.gate, (size_t) hc, "gate"}, {out.gated, (size_t) hc_dim, "gated"},
375        {out.normalized, (size_t) hc_dim, "normalized"}, {out.conv, (size_t) hc_dim, "conv"},
376        {out.result, (size_t) hc_dim, "result"}
377    };
378    for (const auto& item : exports) {
379        if (overlap(item.pointer, item.count * sizeof(float), scratch, (size_t) ple_block_scratch_bytes()))
380            throw std::invalid_argument(std::string("ple_block: output ") + item.name + " overlaps scratch");
381    }
382    if (native_key) {
383        const size_t native_bytes = native_q8_1_bytes(n_embd);
384        const size_t weight_bytes = native_mmvq_weight_bytes(w.key_native_type, n_embd, hc_dim);
385        if ((reinterpret_cast<uintptr_t>(w.key_native_data) & 3u) ||
386            (reinterpret_cast<uintptr_t>(w.key_native_q8_1) & 3u))
387            throw std::invalid_argument("ple_block: native key buffers require four-byte alignment");
388        const struct Region { const void* pointer; size_t bytes; } regions[] = {
389            {scratch, (size_t) ple_block_scratch_bytes()}, {emb, (size_t) n_embd * 4},
390            {hidden, (size_t) hc_dim * 4}, {hist_rows, (size_t) NG_HIST * hc_dim * 4},
391            {w.key_native_data, weight_bytes}, {w.value_bf16, (size_t) n_embd * n_embd * 2},
392            {w.norm_key, (size_t) hc_dim * 4}, {w.norm_query, (size_t) hc_dim * 4},
393            {w.norm_conv, (size_t) hc_dim * 4}, {w.conv1d_f16, (size_t) PLE_CONV_KERNEL * hc_dim * 2}
394        };
395        for (const auto& region : regions)
396            if (overlap(w.key_native_q8_1, native_bytes, region.pointer, region.bytes))
397                throw std::invalid_argument("ple_block: native key scratch overlaps workspace, input or weight");
398        for (const auto& item : exports)
399            if (overlap(w.key_native_q8_1, native_bytes, item.pointer, item.count * sizeof(float)))
400                throw std::invalid_argument(std::string("ple_block: native key scratch overlaps output ") + item.name);
401    }
402    uint8_t* base = (uint8_t*) scratch;
403    float* d_scratch = (float*) base;
404    uint8_t* d_act = base + ((float_bytes + 15) & ~(size_t) 15);
405    uint16_t* d_emb16 = (uint16_t*) (d_act + ((q8_bytes + 15) & ~(size_t) 15));
406    float* d_key = d_scratch;
407    float* d_query = d_key + hc_dim;
408    float* d_norm = d_query + hc_dim;
409    float* d_gated = d_norm + hc_dim;
410    float* d_conv = d_gated + hc_dim;
411    float* d_value = d_conv + hc_dim;
412    float* d_gate = d_value + n_embd;
413
414    // ---- key = grouped_norm(ple_key @ emb). The optional native projection
415    // follows pinned CUDA Q8_1 MMVQ; the default retains its canonical Q8_0 path.
416    if (w.pre_key != nullptr) {
417        /*
418        DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API.
419        While the origin API might be synchronous, it depends on the type of
420        operand memory, so you may need to call wait() on event return by memcpy
421        API to ensure synchronization behavior.
422        */
423        st->memcpy(d_key, w.pre_key, (size_t)hc_dim * sizeof(float));
424    } else if (w.key_bf16 != nullptr) {
425        bf16_gemv_fp32_mmvf(emb, w.key_bf16, d_key, n_embd, hc_dim, stream);
426    } else if (native_key) {
427        native_quantize_q8_1(emb, w.key_native_q8_1, n_embd, 1, stream);
428        native_mmvq(w.key_native_type, w.key_native_data, w.key_native_q8_1,
429                    d_key, n_embd, hc_dim, 1, stream);
430    } else {
431        quantize_q8_0(emb, d_act, n_embd, st);
432        s2_gemv_q8(d_act, w.key_codes, w.key_scales, d_key, n_embd, hc_dim, 8, st);
433    }
434    if (!native_postops) {
435        {
436            auto exp_props = sycl::ext::oneapi::experimental::properties{
437                sycl::ext::oneapi::experimental::use_root_sync};
438            dpct::has_capability_or_fail(st->get_device(),
439                                         {sycl::aspect::fp64});
440
441            strata::kprof::kp(st, __FILE__, __func__, __LINE__)->submit([&](sycl::handler &cgh) {
442                auto NG_RMS_EPS_ct4 = NG_RMS_EPS;
443
444                cgh.parallel_for<dpct_kernel_name<class gnorm_kernel_e2f600>>(
445                    sycl::nd_range<3>(sycl::range(1, 1, hc) *
446                                          sycl::range(1, 1, THREADS),
447                                      sycl::range(1, 1, THREADS)),
448                    exp_props,
449                    [=](sycl::nd_item<3> item_ct1)
450                        [[sycl::reqd_sub_group_size(32)]] {
451                            gnorm_kernel(d_key, w.norm_key, d_key, n_embd,
452                                         NG_RMS_EPS_ct4);
453                        });
454            });
455        }
456        {
457            auto exp_props = sycl::ext::oneapi::experimental::properties{
458                sycl::ext::oneapi::experimental::use_root_sync};
459            dpct::has_capability_or_fail(st->get_device(),
460                                         {sycl::aspect::fp64});
461
462            strata::kprof::kp(st, __FILE__, __func__, __LINE__)->submit([&](sycl::handler &cgh) {
463                auto NG_RMS_EPS_ct4 = NG_RMS_EPS;
464
465                cgh.parallel_for<dpct_kernel_name<class gnorm_kernel_92a6ef>>(
466                    sycl::nd_range<3>(sycl::range(1, 1, hc) *
467                                          sycl::range(1, 1, THREADS),
468                                      sycl::range(1, 1, THREADS)),
469                    exp_props,
470                    [=](sycl::nd_item<3> item_ct1)
471                        [[sycl::reqd_sub_group_size(32)]] {
472                            gnorm_kernel(hidden, w.norm_query, d_query, n_embd,
473                                         NG_RMS_EPS_ct4);
474                        });
475            });
476        }
477    }
478
479    // The value projection's independent option leaves the nonlinear PLE operations unchanged.
480    if (w.pre_value != nullptr) {
481        /*
482        DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API.
483        While the origin API might be synchronous, it depends on the type of
484        operand memory, so you may need to call wait() on event return by memcpy
485        API to ensure synchronization behavior.
486        */
487        st->memcpy(d_value, w.pre_value, (size_t)n_embd * sizeof(float));
488    } else if (native_bf16) {
489        bf16_gemv_fp32_mmvf(emb, w.value_bf16, d_value, n_embd, n_embd, stream);
490    } else {
491        {
492            auto exp_props = sycl::ext::oneapi::experimental::properties{
493                sycl::ext::oneapi::experimental::use_root_sync};
494
495            strata::kprof::kp(st, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class to_bf16_kernel_ab93ff>>(
496                sycl::nd_range<3>(
497                    sycl::range(1, 1, (n_embd + THREADS - 1) / THREADS) *
498                        sycl::range(1, 1, THREADS),
499                    sycl::range(1, 1, THREADS)),
500                exp_props, [=](sycl::nd_item<3> item_ct1) {
501                    to_bf16_kernel(emb, d_emb16, n_embd);
502                });
503        }
504        {
505            auto exp_props = sycl::ext::oneapi::experimental::properties{
506                sycl::ext::oneapi::experimental::use_root_sync};
507            dpct::has_capability_or_fail(st->get_device(),
508                                         {sycl::aspect::fp64});
509
510            strata::kprof::kp(st, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class bf16_gemv_kernel_47d04d>>(
511                sycl::nd_range<3>(
512                    sycl::range(1, 1, (n_embd + THREADS - 1) / THREADS) *
513                        sycl::range(1, 1, THREADS),
514                    sycl::range(1, 1, THREADS)),
515                exp_props, [=](sycl::nd_item<3> item_ct1) {
516                    bf16_gemv_kernel(d_emb16, w.value_bf16, d_value, n_embd,
517                                     n_embd);
518                });
519        }
520    }
521
522    const float* normalized_key = d_key;
523    if (native_postops) {
524        // The key norm has a distinct destination; temporary query storage can
525        // be reused for normalized gated values after the gate consumes it.
526        NativePlePostopsBuffers buffers{d_query,d_norm,d_gate,d_gated,d_norm,d_conv,out.result};
527        native_ple_postops(d_key,hidden,d_value,hist_rows,w,buffers,stream);
528        normalized_key = d_query;
529    } else {
530        {
531            auto exp_props = sycl::ext::oneapi::experimental::properties{
532                sycl::ext::oneapi::experimental::use_root_sync};
533            dpct::has_capability_or_fail(st->get_device(),
534                                         {sycl::aspect::fp64});
535
536            strata::kprof::kp(st, __FILE__, __func__, __LINE__)->submit([&](sycl::handler &cgh) {
537                auto sqrtf_float_n_embd_ct4 = 1.0f / sqrtf((float)n_embd);
538
539                cgh.parallel_for<dpct_kernel_name<class gate_kernel_ce83eb>>(
540                    sycl::nd_range<3>(sycl::range(1, 1, hc) *
541                                          sycl::range(1, 1, THREADS),
542                                      sycl::range(1, 1, THREADS)),
543                    exp_props,
544                    [=](sycl::nd_item<3> item_ct1)
545                        [[sycl::reqd_sub_group_size(32)]] {
546                            gate_kernel(d_key, d_query, d_gate, n_embd,
547                                        sqrtf_float_n_embd_ct4);
548                        });
549            });
550        }
551        {
552            auto exp_props = sycl::ext::oneapi::experimental::properties{
553                sycl::ext::oneapi::experimental::use_root_sync};
554
555            strata::kprof::kp(st, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class bcast_kernel_79d1c2>>(
556                sycl::nd_range<3>(
557                    sycl::range(1, 1, (hc_dim + THREADS - 1) / THREADS) *
558                        sycl::range(1, 1, THREADS),
559                    sycl::range(1, 1, THREADS)),
560                exp_props, [=](sycl::nd_item<3> item_ct1) {
561                    bcast_kernel(d_value, d_gate, d_gated, n_embd, hc);
562                });
563        }
564        {
565            auto exp_props = sycl::ext::oneapi::experimental::properties{
566                sycl::ext::oneapi::experimental::use_root_sync};
567            dpct::has_capability_or_fail(st->get_device(),
568                                         {sycl::aspect::fp64});
569
570            strata::kprof::kp(st, __FILE__, __func__, __LINE__)->submit([&](sycl::handler &cgh) {
571                auto NG_RMS_EPS_ct4 = NG_RMS_EPS;
572
573                cgh.parallel_for<dpct_kernel_name<class gnorm_kernel_dda9b4>>(
574                    sycl::nd_range<3>(sycl::range(1, 1, hc) *
575                                          sycl::range(1, 1, THREADS),
576                                      sycl::range(1, 1, THREADS)),
577                    exp_props,
578                    [=](sycl::nd_item<3> item_ct1)
579                        [[sycl::reqd_sub_group_size(32)]] {
580                            gnorm_kernel(d_gated, w.norm_conv, d_norm, n_embd,
581                                         NG_RMS_EPS_ct4);
582                        });
583            });
584        }
585        {
586            auto exp_props = sycl::ext::oneapi::experimental::properties{
587                sycl::ext::oneapi::experimental::use_root_sync};
588
589            strata::kprof::kp(st, __FILE__, __func__, __LINE__)->submit([&](sycl::handler &cgh) {
590                auto PLE_CONV_KERNEL_ct5 = PLE_CONV_KERNEL;
591                auto NGRAM_SIZE_ct6 = NGRAM_SIZE;
592                auto NG_HIST_ct7 = NG_HIST;
593
594                cgh.parallel_for<dpct_kernel_name<class conv_kernel_f83a85>>(
595                    sycl::nd_range<3>(
596                        sycl::range(1, 1, (hc_dim + THREADS - 1) / THREADS) *
597                            sycl::range(1, 1, THREADS),
598                        sycl::range(1, 1, THREADS)),
599                    exp_props, [=](sycl::nd_item<3> item_ct1) {
600                        conv_kernel(hist_rows, d_norm, w.conv1d_f16, d_conv,
601                                    hc_dim, PLE_CONV_KERNEL_ct5, NGRAM_SIZE_ct6,
602                                    NG_HIST_ct7);
603                    });
604            });
605        }
606        {
607            auto exp_props = sycl::ext::oneapi::experimental::properties{
608                sycl::ext::oneapi::experimental::use_root_sync};
609
610            strata::kprof::kp(st, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class add3_kernel_26c4c6>>(
611                sycl::nd_range<3>(
612                    sycl::range(1, 1, (hc_dim + THREADS - 1) / THREADS) *
613                        sycl::range(1, 1, THREADS),
614                    sycl::range(1, 1, THREADS)),
615                exp_props, [=](sycl::nd_item<3> item_ct1) {
616                    add3_kernel(hidden, d_gated, d_conv, out.result, hc_dim);
617                });
618        }
619    }
620
621    // ---- the intermediates the oracle comparison needs.  `key` is the NORMALISED key, because the source's
622    //      `cb(key, ...)` capture is after `gnorm`; `value` is the projection before the gate.  Each stage the
623    //      oracle records is reproduced here so a mismatch can be attributed instead of guessed at.
624    /*
625    DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API. While
626    the origin API might be synchronous, it depends on the type of operand
627    memory, so you may need to call wait() on event return by memcpy API to
628    ensure synchronization behavior.
629    */
630    if (out.key) ck(DPCT_CHECK_ERROR(st->memcpy(out.key, normalized_key,
631                                                hc_dim * sizeof(float))),
632                    "key");
633    if (out.value)
634        /*
635        DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API.
636        While the origin API might be synchronous, it depends on the type of
637        operand memory, so you may need to call wait() on event return by memcpy
638        API to ensure synchronization behavior.
639        */
640        ck(DPCT_CHECK_ERROR(
641               st->memcpy(out.value, d_value, n_embd * sizeof(float))),
642           "value");
643    /*
644    DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API. While
645    the origin API might be synchronous, it depends on the type of operand
646    memory, so you may need to call wait() on event return by memcpy API to
647    ensure synchronization behavior.
648    */
649    if (out.gate)
650        ck(DPCT_CHECK_ERROR(st->memcpy(out.gate, d_gate, hc * sizeof(float))),
651           "gate");
652    if (out.gated)
653        /*
654        DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API.
655        While the origin API might be synchronous, it depends on the type of
656        operand memory, so you may need to call wait() on event return by memcpy
657        API to ensure synchronization behavior.
658        */
659        ck(DPCT_CHECK_ERROR(
660               st->memcpy(out.gated, d_gated, hc_dim * sizeof(float))),
661           "gated");
662    if (out.normalized)
663        /*
664        DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API.
665        While the origin API might be synchronous, it depends on the type of
666        operand memory, so you may need to call wait() on event return by memcpy
667        API to ensure synchronization behavior.
668        */
669        ck(DPCT_CHECK_ERROR(
670               st->memcpy(out.normalized, d_norm, hc_dim * sizeof(float))),
671           "norm");
672    if (out.conv)
673        /*
674        DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API.
675        While the origin API might be synchronous, it depends on the type of
676        operand memory, so you may need to call wait() on event return by memcpy
677        API to ensure synchronization behavior.
678        */
679        ck(DPCT_CHECK_ERROR(
680               st->memcpy(out.conv, d_conv, hc_dim * sizeof(float))),
681           "conv");
682
683    /*
684    DPCT1010: SYCL uses exceptions to report errors and does not use the
685    error codes. The cudaGetLastError function call was replaced with 0. You
686    need to rewrite this code.
687    */
688    ck(0, "launch");
689    // **NO `cudaStreamSynchronize` HERE.**  It was there to make the function self-contained for the parity
690    // test, and inside a capture it is an error - a caller that wants the result immediately synchronises
691    // itself, and the engine's caller does not want that at all.
692}
693
694void ple_block_projected(const float* projected_key, const float* projected_value, const float* hidden,
695                         const float* hist_rows, const PleWeights& w, PleOut& out, void* scratch, void* stream) {
696    if (!projected_key || !projected_value || !hidden || !hist_rows || !out.result || !scratch) return;
697    const int n_embd = NG_N_EMBD, hc = NG_HC, hc_dim = NG_HC_DIM;
698    float* d_scratch = (float*) scratch;
699    float* d_key = d_scratch;
700    float* d_query = d_key + hc_dim;
701    float* d_norm = d_query + hc_dim;
702    float* d_gated = d_norm + hc_dim;
703    float* d_conv = d_gated + hc_dim;
704    float* d_value = d_conv + hc_dim;
705    float* d_gate = d_value + n_embd;
706    float* norm_dst = out.normalized ? out.normalized : d_norm;
707    NativePlePostopsBuffers buffers{d_query, norm_dst, d_gate, d_gated, norm_dst, d_conv, out.result};
708    native_ple_postops(projected_key, hidden, projected_value, hist_rows, w, buffers, stream);
709}
710
711}  // namespace strata::kernels