okami.mom/strata

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

Niko1221Merge f-q4-geometry (fc1c4e429): the model shape is fixed at build time (-DSTRATA_GEOMETRY / -DSTRATA_GEOMETRY_FILE); the default Flash-Next build is unchanged (CUDA SASS 3573/3573, HIP gfx1201 3920/3920, gfx1151 path-string offsets only, SYCL 22/22 checksums, Metal 10/10 tokens, CUDA 130/130 tokens); Qwen4 test shapes q4_lite/q4_mid/q4_big pass logits gate 2 on CUDA (Qwen4 prep)4dad59ab3

main
22.4 KiB413 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#include "strata/kernels/ple.hpp"
17#include "strata/kernels/bf16_gemv.hpp"
18#include "strata/kernels/f16_bits.hpp"
19#include "strata/kernels/ngram.hpp"
20#include "strata/kernels/quantize_act.hpp"
21#include "strata/kernels/s2_gemv_q8.hpp"
22#include "strata/kernels/native_mmvq.hpp"
23#include "strata/kernels/native_ple_postops.hpp"
24
25#include <cuda_runtime.h>
26#include <cuda_fp16.h>
27
28#include <cmath>
29#include <cstdio>
30#include <cstdlib>
31#include <stdexcept>
32#include <string>
33
34namespace strata::kernels {
35namespace {
36
37constexpr int THREADS = 256;
38bool native_bf16 = false;
39bool native_postops = false;
40
41bool overlap(const void* a, size_t a_bytes, const void* b, size_t b_bytes) {
42    if (a == nullptr || b == nullptr || a_bytes == 0 || b_bytes == 0) return false;
43    const uintptr_t aa = reinterpret_cast<uintptr_t>(a), bb = reinterpret_cast<uintptr_t>(b);
44    return aa < bb ? bb - aa < a_bytes : aa - bb < b_bytes;
45}
46
47__global__ void history_advance_kernel(float* __restrict__ history, const float* __restrict__ normalized) {
48    const int channel = blockIdx.x * blockDim.x + threadIdx.x;
49    if (channel >= NG_HC_DIM) return;
50    float* column = history + (size_t) channel * NG_HIST;
51    for (int row = 0; row + 1 < NG_HIST; ++row) column[row] = column[row + 1];
52    column[NG_HIST - 1] = normalized[channel];
53}
54
55__device__ __forceinline__ uint16_t bf16_bits(float f) {
56    uint32_t i;
57    memcpy(&i, &f, 4);
58    i = (i + ((i >> 16) & 1u) + 0x7FFFu) & 0xFFFF0000u;
59    return (uint16_t) (i >> 16);
60}
61
62__device__ __forceinline__ float bf16_float(uint16_t h) {
63    const uint32_t i = (uint32_t) h << 16;
64    float f;
65    memcpy(&f, &i, 4);
66    return f;
67}
68
69__device__ __forceinline__ float silu_f(float x) { return x / (1.0f + expf(-x)); }
70
71/// Block-wide sum in double, broadcast to all threads.  The leading `__syncthreads` matters: the result is
72/// read out of `scratch[0]` and a later call reuses the array, so without a barrier a fast thread can
73/// overwrite it before a slow one has read it - invisible in most runs and a slightly different norm when it
74/// fires.
75__device__ double block_sum(double v, double* scratch) {
76    __syncthreads();
77    const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5;
78    for (int off = 16; off > 0; off >>= 1) v += __shfl_down_sync(0xFFFFFFFFu, v, off);
79    if (lane == 0) scratch[warp] = v;
80    __syncthreads();
81    const int nw = ((int) blockDim.x + 31) >> 5;
82    v = (threadIdx.x < nw) ? scratch[threadIdx.x] : 0.0;
83    if (warp == 0)
84        for (int off = 16; off > 0; off >>= 1) v += __shfl_down_sync(0xFFFFFFFFu, v, off);
85    if (threadIdx.x == 0) scratch[0] = v;
86    __syncthreads();
87    return scratch[0];
88}
89
90/// `grouped_norm`, ONE BLOCK PER STREAM.  The ggml form is `reshape_3d(x, n_embd, hc, T)` then
91/// `rms_norm(..., eps) * w`, so ne0 = n_embd is the reduction axis and each hc stream is normalised on its
92/// own.  In the flat ggml layout (ne0 fastest) stream c occupies [c*n_embd, (c+1)*n_embd).
93__global__ void gnorm_kernel(const float* __restrict__ x, const float* __restrict__ w,
94                             float* __restrict__ y, int n_embd, float eps) {
95    __shared__ double scratch[8];
96    const int c = blockIdx.x;
97    const float* xc = x + (size_t) c * n_embd;
98    const float* wc = w + (size_t) c * n_embd;
99    float* yc = y + (size_t) c * n_embd;
100
101    double acc = 0.0;
102    for (int d = threadIdx.x; d < n_embd; d += blockDim.x) {
103        // The PRODUCT is rounded in f32 before it is widened - `(ggml_float)(x[i00]*x[i00])`.
104        const float sq = xc[d] * xc[d];
105        acc += (double) sq;
106    }
107    const float mean = (float) (block_sum(acc, scratch) / (double) n_embd);
108    const float scale = 1.0f / sqrtf(mean + eps);
109    for (int d = threadIdx.x; d < n_embd; d += blockDim.x) yc[d] = xc[d] * scale * wc[d];
110}
111
112/// `s[c] = sum_d key[c][d]*query[c][d] / sqrt(n_embd)`, then the signed square root and the sigmoid.
113///
114/// `mag = sqrt(clamp(|s|, 1e-6, inf))` and `gate = sigmoid(sgn(s) * mag)`.  The clamp is a floor on |s|, so
115/// it only bites near zero; the SIGN is carried separately, which is what keeps the gate symmetric about 0.5.
116__global__ void gate_kernel(const float* __restrict__ key, const float* __restrict__ query,
117                            float* __restrict__ gate, int n_embd, float inv_sqrt_n) {
118    __shared__ double scratch[8];
119    const int c = blockIdx.x;
120    const float* kc = key + (size_t) c * n_embd;
121    const float* qc = query + (size_t) c * n_embd;
122    double acc = 0.0;
123    for (int d = threadIdx.x; d < n_embd; d += blockDim.x) acc += (double) (kc[d] * qc[d]);
124    const float s = (float) (block_sum(acc, scratch) / (double) 1.0) * inv_sqrt_n;
125    const float mag = sqrtf(fmaxf(fabsf(s), 1e-6f));
126    const float sgn = (s > 0.0f) ? 1.0f : ((s < 0.0f) ? -1.0f : 0.0f);
127    if (threadIdx.x == 0) gate[c] = 1.0f / (1.0f + expf(-(sgn * mag)));
128}
129
130/// `gated[c][d] = value[d] * gate[c]` - the value broadcast across the hc streams.
131__global__ void bcast_kernel(const float* __restrict__ value, const float* __restrict__ gate,
132                             float* __restrict__ gated, int n_embd, int hc) {
133    const int i = blockIdx.x * blockDim.x + threadIdx.x;
134    if (i >= n_embd * hc) return;
135    gated[i] = value[i % n_embd] * gate[i / n_embd];
136}
137
138/// The depthwise causal dilated conv, then SiLU.  One thread per channel.
139///
140/// `out[c] = sum_k kW[k][c] * terms[t - (kern-1-k)*dil][c]` with `t = hist` (the first new position), so tap k
141/// reads row `hist - (kern-1-k)*dil` of `[history | new]`.  For the real geometry (kern 4, dil 3, hist 9) the
142/// four taps read rows 0, 3, 6 and 9 - and row 9 is the NEW row, which is the only one beyond the history.
143/// That is why no `terms` buffer is built: three taps come from the caller's history and one from `norm`.
144///
145/// `kW` IS GGML-NATIVE: `kW[k + kern*c]`.  The manifest's shape is [4, 10240] with ne0 = 4 fast, and
146/// `ref/ngram.py`'s (4, 10240) numpy `kernel[k][c]` is the TRANSPOSE of that.  The source's own view
147/// (`ggml_view_2d(model.layers[il].ple_conv1d, 1, hc_dim, nb[1], k*nb[0])`) settles which one is meant.
148__global__ void conv_kernel(const float* __restrict__ hist, const float* __restrict__ norm,
149                            const uint16_t* __restrict__ kW, float* __restrict__ out, int hc_dim, int kern,
150                            int dil, int nhist) {
151    const int c = blockIdx.x * blockDim.x + threadIdx.x;
152    if (c >= hc_dim) return;
153    float acc = 0.0f;
154    for (int k = 0; k < kern; ++k) {
155        const int row = nhist - (kern - 1 - k) * dil;      // tap 0 reads the FURTHEST back
156        // ROW-FASTEST: `hist[row + nhist*c]`.  The conv state is `ggml_reshape_3d(state, d_conv-1,
157        // conv_channels, n_seqs)`, so ne0 = hist varies fastest and the flat index is row + hist*channel.
158        // Channel-slowest (`row*hc_dim + c`) is the natural thing to write and would read a transposed state -
159        // `ple_layer_xcheck.cpp` L79-83 records getting this wrong once already.
160        const float v = (row == nhist) ? norm[c] : hist[(size_t) row + (size_t) nhist * c];
161        acc += f32_from_f16(kW[k + kern * c]) * v;
162    }
163    out[c] = silu_f(acc);
164}
165
166/// `result = hidden + gated + conv`, elementwise over hc_dim.
167__global__ void add3_kernel(const float* __restrict__ hidden, const float* __restrict__ gated,
168                            const float* __restrict__ conv, float* __restrict__ result, int n) {
169    const int i = blockIdx.x * blockDim.x + threadIdx.x;
170    if (i < n) result[i] = hidden[i] + gated[i] + conv[i];
171}
172
173/// `y[o] = sum_i bf16(x[i]) * bf16(w[o*n_in + i])`.  The weight is BF16 and so is the ACTIVATION, which is
174/// the contract for a BF16 tensor (`docs/activation-contract.md`); with both sides bf16 the products are
175/// exact in f32 and only the summation order differs from ggml's.
176__global__ void bf16_gemv_kernel(const uint16_t* __restrict__ x, const uint16_t* __restrict__ w,
177                                 float* __restrict__ y, int n_in, int n_out) {
178    const int o = blockIdx.x * blockDim.x + threadIdx.x;
179    if (o >= n_out) return;
180    const uint16_t* row = w + (size_t) o * n_in;
181    double acc = 0.0;
182    for (int i = 0; i < n_in; ++i) acc += (double) bf16_float(x[i]) * (double) bf16_float(row[i]);
183    y[o] = (float) acc;
184}
185
186__global__ void to_bf16_kernel(const float* __restrict__ x, uint16_t* __restrict__ y, int n) {
187    const int i = blockIdx.x * blockDim.x + threadIdx.x;
188    if (i < n) y[i] = bf16_bits(x[i]);
189}
190
191void ck(cudaError_t e, const char* what) {
192    if (e != cudaSuccess) {
193        std::fprintf(stderr, "ple_block: %s: %s\n", what, cudaGetErrorString(e));
194        std::exit(1);
195    }
196}
197
198}  // namespace
199
200void ple_set_native_bf16(bool enabled) { native_bf16 = enabled; }
201bool ple_native_bf16_enabled() { return native_bf16; }
202void ple_set_native_postops(bool enabled) { native_postops = enabled; }
203bool ple_native_postops_enabled() { return native_postops; }
204
205void ple_history_advance(float* hist, const float* normalized, void* stream) {
206    if (hist == nullptr || normalized == nullptr)
207        throw std::invalid_argument("ple_history_advance: null history or normalized input");
208    if (overlap(hist, (size_t) NG_HIST * NG_HC_DIM * sizeof(float),
209                normalized, (size_t) NG_HC_DIM * sizeof(float)))
210        throw std::invalid_argument("ple_history_advance: history and normalized input overlap");
211    history_advance_kernel<<<(NG_HC_DIM + THREADS - 1) / THREADS, THREADS, 0, (cudaStream_t) stream>>>(hist, normalized);
212    ck(cudaGetLastError(), "history advance launch");
213}
214
215bool ple_block_available() {
216    int n = 0;
217    return cudaGetDeviceCount(&n) == cudaSuccess && n > 0;
218}
219
220uint64_t ple_block_scratch_bytes() {
221    // five hc_dim floats + n_embd + hc, then the Q8 activation image, then the BF16 embedding copy, each
222    // 16-byte aligned because `d_scratch` is cast to `float*` and `d_act` to `uint8_t*` at those offsets.
223    const size_t f = (size_t) (5 * NG_HC_DIM + NG_N_EMBD + NG_HC) * sizeof(float);
224    const size_t q = (size_t) (NG_N_EMBD / 32) * 34;
225    const size_t e = (size_t) NG_N_EMBD * sizeof(uint16_t);
226    return ((f + 15) & ~(size_t) 15) + ((q + 15) & ~(size_t) 15) + e + 256;
227}
228
229void ple_block(const float* emb, const float* hidden, const float* hist_rows, const PleWeights& w,
230               PleOut& out, void* scratch, void* stream) {
231    const bool native_key = w.key_native_data != nullptr && w.key_bf16 == nullptr;
232    if (native_key && (!emb || !hidden || !hist_rows || !out.result || !scratch || !stream ||
233                       !w.key_native_q8_1 ||
234                       (w.key_native_type != 42 && w.key_native_type != 18 && w.key_native_type != 23 &&
235                        w.key_native_type != 8)))
236        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");
237    if (emb == nullptr || hidden == nullptr || hist_rows == nullptr || out.result == nullptr) return;
238    const int n_embd = NG_N_EMBD, hc = NG_HC, hc_dim = NG_HC_DIM;
239    static_assert(NG_N_EMBD % 32 == 0 && NG_HC_DIM == NG_HC * NG_N_EMBD, "native PLE key geometry changed");
240    const size_t float_bytes = (size_t) (5 * hc_dim + n_embd + hc) * sizeof(float);
241    cudaStream_t st = (cudaStream_t) stream;
242
243    // One allocation for every intermediate.
244    //
245    // THE ENGINE WILL NOT DO THIS.  P2.T10 requires zero token-path allocations, and the fix is the same one
246    // `gr_read` already uses: a caller-owned workspace carved once at startup.  It is done this way here
247    // because this function's job in P2.S4 is to be CORRECT and comparable against the oracle, and matching
248    // `shared_expert.cu`'s existing shape keeps the diff small.  Recorded rather than hidden.
249    //
250    // FIVE SEPARATE hc_dim BUFFERS, deliberately.  `key` and `normalized` are both needed at the end for the
251    // oracle comparison, so aliasing one onto the other - which the first version did - silently returns the
252    // WRONG `key`.  Two buffers of the same size look like an obvious saving and the only thing it saves is
253    // 40 KB.
254    // **THE WORKSPACE IS CARVED FROM THE CALLER'S, NOT ALLOCATED.**  Three `cudaMalloc`s and a
255    // `cudaStreamSynchronize` used to live here, and inside a stream capture both are errors: the engine
256    // reported `ple_block: scratch: operation not permitted when stream is capturing`, and a token-path
257    // allocation is a P2.T10 violation besides.  The comment this replaces already said the right shape was
258    // "a caller-owned workspace carved once at startup"; this is that.
259    const size_t q8_bytes = (size_t) (n_embd / 32) * 34;
260    if (scratch == nullptr) {
261        std::fprintf(stderr, "ple_block: scratch is null; the caller owns it (see ple_block_scratch_bytes)\n");
262        std::exit(1);
263    }
264    const struct Export { const float* pointer; size_t count; const char* name; } exports[] = {
265        {out.key, (size_t) hc_dim, "key"}, {out.value, (size_t) n_embd, "value"},
266        {out.gate, (size_t) hc, "gate"}, {out.gated, (size_t) hc_dim, "gated"},
267        {out.normalized, (size_t) hc_dim, "normalized"}, {out.conv, (size_t) hc_dim, "conv"},
268        {out.result, (size_t) hc_dim, "result"}
269    };
270    for (const auto& item : exports) {
271        if (overlap(item.pointer, item.count * sizeof(float), scratch, (size_t) ple_block_scratch_bytes()))
272            throw std::invalid_argument(std::string("ple_block: output ") + item.name + " overlaps scratch");
273    }
274    if (native_key) {
275        const size_t native_bytes = native_q8_1_bytes(n_embd);
276        const size_t weight_bytes = native_mmvq_weight_bytes(w.key_native_type, n_embd, hc_dim);
277        if ((reinterpret_cast<uintptr_t>(w.key_native_data) & 3u) ||
278            (reinterpret_cast<uintptr_t>(w.key_native_q8_1) & 3u))
279            throw std::invalid_argument("ple_block: native key buffers require four-byte alignment");
280        const struct Region { const void* pointer; size_t bytes; } regions[] = {
281            {scratch, (size_t) ple_block_scratch_bytes()}, {emb, (size_t) n_embd * 4},
282            {hidden, (size_t) hc_dim * 4}, {hist_rows, (size_t) NG_HIST * hc_dim * 4},
283            {w.key_native_data, weight_bytes}, {w.value_bf16, (size_t) n_embd * n_embd * 2},
284            {w.norm_key, (size_t) hc_dim * 4}, {w.norm_query, (size_t) hc_dim * 4},
285            {w.norm_conv, (size_t) hc_dim * 4}, {w.conv1d_f16, (size_t) PLE_CONV_KERNEL * hc_dim * 2}
286        };
287        for (const auto& region : regions)
288            if (overlap(w.key_native_q8_1, native_bytes, region.pointer, region.bytes))
289                throw std::invalid_argument("ple_block: native key scratch overlaps workspace, input or weight");
290        for (const auto& item : exports)
291            if (overlap(w.key_native_q8_1, native_bytes, item.pointer, item.count * sizeof(float)))
292                throw std::invalid_argument(std::string("ple_block: native key scratch overlaps output ") + item.name);
293    }
294    uint8_t* base = (uint8_t*) scratch;
295    float* d_scratch = (float*) base;
296    uint8_t* d_act = base + ((float_bytes + 15) & ~(size_t) 15);
297    uint16_t* d_emb16 = (uint16_t*) (d_act + ((q8_bytes + 15) & ~(size_t) 15));
298    float* d_key = d_scratch;
299    float* d_query = d_key + hc_dim;
300    float* d_norm = d_query + hc_dim;
301    float* d_gated = d_norm + hc_dim;
302    float* d_conv = d_gated + hc_dim;
303    float* d_value = d_conv + hc_dim;
304    float* d_gate = d_value + n_embd;
305
306    // ---- key = grouped_norm(ple_key @ emb). The optional native projection
307    // follows pinned CUDA Q8_1 MMVQ; the default retains its canonical Q8_0 path.
308    if (w.pre_key != nullptr) {
309        cudaMemcpyAsync(d_key, w.pre_key, (size_t) hc_dim * sizeof(float), cudaMemcpyDeviceToDevice, st);
310    } else if (w.key_bf16 != nullptr) {
311        bf16_gemv_fp32_mmvf(emb, w.key_bf16, d_key, n_embd, hc_dim, stream);
312    } else if (native_key) {
313        native_quantize_q8_1(emb, w.key_native_q8_1, n_embd, 1, stream);
314        native_mmvq(w.key_native_type, w.key_native_data, w.key_native_q8_1,
315                    d_key, n_embd, hc_dim, 1, stream);
316    } else {
317        quantize_q8_0(emb, d_act, n_embd, st);
318        s2_gemv_q8(d_act, w.key_codes, w.key_scales, d_key, n_embd, hc_dim, 8, st);
319    }
320    if (!native_postops) {
321        gnorm_kernel<<<hc, THREADS, 0, st>>>(d_key, w.norm_key, d_key, n_embd, NG_RMS_EPS);
322        gnorm_kernel<<<hc, THREADS, 0, st>>>(hidden, w.norm_query, d_query, n_embd, NG_RMS_EPS);
323    }
324
325    // The value projection's independent option leaves the nonlinear PLE operations unchanged.
326    if (w.pre_value != nullptr) {
327        cudaMemcpyAsync(d_value, w.pre_value, (size_t) n_embd * sizeof(float), cudaMemcpyDeviceToDevice, st);
328    } else if (native_bf16) {
329        bf16_gemv_fp32_mmvf(emb, w.value_bf16, d_value, n_embd, n_embd, stream);
330    } else {
331        to_bf16_kernel<<<(n_embd + THREADS - 1) / THREADS, THREADS, 0, st>>>(emb, d_emb16, n_embd);
332        bf16_gemv_kernel<<<(n_embd + THREADS - 1) / THREADS, THREADS, 0, st>>>(d_emb16, w.value_bf16, d_value,
333                                                                              n_embd, n_embd);
334    }
335
336    const float* normalized_key = d_key;
337    if (native_postops) {
338        // The key norm has a distinct destination; temporary query storage can
339        // be reused for normalized gated values after the gate consumes it.
340        NativePlePostopsBuffers buffers{d_query,d_norm,d_gate,d_gated,d_norm,d_conv,out.result};
341        native_ple_postops(d_key,hidden,d_value,hist_rows,w,buffers,stream);
342        normalized_key = d_query;
343    } else {
344        gate_kernel<<<hc, THREADS, 0, st>>>(d_key, d_query, d_gate, n_embd, 1.0f / sqrtf((float) n_embd));
345        bcast_kernel<<<(hc_dim + THREADS - 1) / THREADS, THREADS, 0, st>>>(d_value, d_gate, d_gated, n_embd, hc);
346        gnorm_kernel<<<hc, THREADS, 0, st>>>(d_gated, w.norm_conv, d_norm, n_embd, NG_RMS_EPS);
347        conv_kernel<<<(hc_dim + THREADS - 1) / THREADS, THREADS, 0, st>>>(hist_rows, d_norm, w.conv1d_f16, d_conv,
348                                                                         hc_dim, PLE_CONV_KERNEL, NGRAM_SIZE,
349                                                                         NG_HIST);
350        add3_kernel<<<(hc_dim + THREADS - 1) / THREADS, THREADS, 0, st>>>(hidden, d_gated, d_conv, out.result,
351                                                                         hc_dim);
352    }
353
354    // ---- the intermediates the oracle comparison needs.  `key` is the NORMALISED key, because the source's
355    //      `cb(key, ...)` capture is after `gnorm`; `value` is the projection before the gate.  Each stage the
356    //      oracle records is reproduced here so a mismatch can be attributed instead of guessed at.
357    if (out.key) ck(cudaMemcpyAsync(out.key, normalized_key, hc_dim * sizeof(float), cudaMemcpyDeviceToDevice, st), "key");
358    if (out.value)
359        ck(cudaMemcpyAsync(out.value, d_value, n_embd * sizeof(float), cudaMemcpyDeviceToDevice, st), "value");
360    if (out.gate) ck(cudaMemcpyAsync(out.gate, d_gate, hc * sizeof(float), cudaMemcpyDeviceToDevice, st), "gate");
361    if (out.gated)
362        ck(cudaMemcpyAsync(out.gated, d_gated, hc_dim * sizeof(float), cudaMemcpyDeviceToDevice, st), "gated");
363    if (out.normalized)
364        ck(cudaMemcpyAsync(out.normalized, d_norm, hc_dim * sizeof(float), cudaMemcpyDeviceToDevice, st), "norm");
365    if (out.conv)
366        ck(cudaMemcpyAsync(out.conv, d_conv, hc_dim * sizeof(float), cudaMemcpyDeviceToDevice, st), "conv");
367
368    ck(cudaGetLastError(), "launch");
369    // **NO `cudaStreamSynchronize` HERE.**  It was there to make the function self-contained for the parity
370    // test, and inside a capture it is an error - a caller that wants the result immediately synchronises
371    // itself, and the engine's caller does not want that at all.
372}
373
374void ple_block_projected(const float* projected_key, const float* projected_value, const float* hidden,
375                         const float* hist_rows, const PleWeights& w, PleOut& out, void* scratch, void* stream) {
376    if (!projected_key || !projected_value || !hidden || !hist_rows || !out.result || !scratch) return;
377    const int n_embd = NG_N_EMBD, hc = NG_HC, hc_dim = NG_HC_DIM;
378    float* d_scratch = (float*) scratch;
379    float* d_key = d_scratch;
380    float* d_query = d_key + hc_dim;
381    float* d_norm = d_query + hc_dim;
382    float* d_gated = d_norm + hc_dim;
383    float* d_conv = d_gated + hc_dim;
384    float* d_value = d_conv + hc_dim;
385    float* d_gate = d_value + n_embd;
386    float* norm_dst = out.normalized ? out.normalized : d_norm;
387    NativePlePostopsBuffers buffers{d_query, norm_dst, d_gate, d_gated, norm_dst, d_conv, out.result};
388    native_ple_postops(projected_key, hidden, projected_value, hist_rows, w, buffers, stream);
389}
390
391namespace {
392__constant__ int8_t kPleIq4Nl[16] = {-127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113};
393// one thread a value: row r, block b (18 bytes: fp16 d, 16 bytes of codes), element j of 32 (j < 16: low nibble of
394// qs[j], else the high nibble of qs[j - 16] - the split halves of iq4nl_dequant_row)
395__global__ void ple_iq4nl_dequant_kernel(const uint8_t* __restrict__ raw, int64_t n, float* __restrict__ out) {
396    const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
397    if (i >= n) return;
398    const int64_t r = i / PLE_HEAD_DIM;
399    const int e = (int) (i - r * PLE_HEAD_DIM), b = e >> 5, j = e & 31;
400    const uint8_t* blk = raw + r * PLE_ROW_BYTES + b * 18;
401    const float d = __half2float(__ushort_as_half((unsigned short) (blk[0] | (blk[1] << 8))));
402    const uint8_t q = blk[2 + (j & 15)];
403    out[i] = d * (float) kPleIq4Nl[j < 16 ? (q & 15) : (q >> 4)];
404}
405}  // namespace
406
407void ple_iq4nl_dequant(const uint8_t* raw, int64_t rows, float* out, void* stream) {
408    const int64_t n = rows * PLE_HEAD_DIM;
409    if (n <= 0) return;
410    ple_iq4nl_dequant_kernel<<<(unsigned) ((n + 255) / 256), 256, 0, (cudaStream_t) stream>>>(raw, n, out);
411}
412
413}  // namespace strata::kernels