okami.mom/strata

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

Niko1221Merge f-037-arc (5eaee81a4)86bed1c92

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