okami.mom/strata

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

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

main
18.0 KiB402 linesraw
1// src/kernels/cuda/gdn.cu - P2.S2: the gated delta-net's non-projection parts.
2//
3// See include/strata/kernels/gdn.hpp for the state layout (S, h_v, S) and for why the recurrence needs no
4// barrier at all: every line of it touches only one (j, h) column, so one thread owns a column end to end.
5#define DPCT_PROFILING_ENABLED
6#include <sycl/sycl.hpp>
7#include "strata/kprof.hpp"
8#include <dpct/dpct.hpp>
9#include "strata/sycl_queue.hpp"
10#include "strata/kernels/gdn.hpp"
11
12#include <cmath>
13#include <cstdio>
14#include <cstdlib>
15
16namespace strata::kernels {
17namespace {
18
19constexpr int JTHREADS = 32;   ///< threads along j, the state's fast axis
20/// Heads staged per block.  **THIS IS A LATENCY-HIDING KNOB, NOT A CAPACITY ONE, AND IT WAS SET WRONG.**
21///
22/// The kernel is one thread per `(h, j)` COLUMN of the state, so the thread count is fixed at
23/// `S * h_v` = 128 * 48 = **6,144** no matter how the work is packed - and `MAX_H` decides only how many of
24/// those columns share a block:
25///
26///     MAX_H = 8   grid = (S/32, h_v/8) = (4, 6)  =  24 blocks x 32 threads  ->  1 warp on 24 of 48 SMs
27///     MAX_H = 1   grid = (S/32, h_v/1) = (4, 48) = 192 blocks x 32 threads  ->  4 warps on every SM
28///
29/// Each thread walks `i` in 0..S-1 TWICE per head with a strided global load each step, so it is entirely
30/// latency-bound: a warp that issues one 128-byte transaction and then waits ~600 cycles needs other warps to
31/// run meanwhile, and at 24 blocks there were none.  Measured 0.2800 ms per GDN block - 10 ms of a 71.5 ms
32/// token, 14%, in a kernel touching 12.6 MB that a 643 GB/s card should do in 0.020 ms.
33///
34/// The arithmetic does not change at all: the same columns are computed by the same code, in different blocks.
35constexpr int MAX_H = 1;       ///< heads staged in shared memory per block
36
37/// ggml_compute_softplus_f32: log1p(exp(x)), with the large-x branch that avoids overflow.
38__dpct_inline__ float softplus_f(float x) {
39    return x > 20.0f ? x : sycl::log1p(sycl::native::exp(x));
40}
41__dpct_inline__ float sigmoid_f(float x) {
42    return 1.0f / (1.0f + sycl::native::exp(-x));
43}
44
45/// One step of the recurrence.  One thread per (h, j) column of the state.
46///
47/// `ks`/`qs` stage `k[idx[h]]` and `q[idx[h]]` for the block's heads.  Within a warp h is constant and j
48/// varies, so the staged row is read with a single broadcast - which is also why the GLOBAL loads of
49/// `q`/`k` are done once per block into shared instead of once per thread.
50__dpct_inline__ void
51gdn_step_kernel(float *__restrict__ state, const float *__restrict__ q,
52                const float *__restrict__ k, const float *__restrict__ v,
53                const float *__restrict__ gate, const float *__restrict__ beta,
54                float *__restrict__ o, int S, int h_k, int h_v) {
55    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
56auto &ks =
57    *sycl::ext::oneapi::group_local_memory_for_overwrite<float[MAX_H][128]>(
58        sycl::ext::oneapi::this_work_item::get_work_group<3>());
59    auto &qs =
60        *sycl::ext::oneapi::group_local_memory_for_overwrite<float[MAX_H][128]>(
61            sycl::ext::oneapi::this_work_item::get_work_group<3>());
62    auto &dec_s =
63        *sycl::ext::oneapi::group_local_memory_for_overwrite<float[MAX_H]>(
64            sycl::ext::oneapi::this_work_item::get_work_group<3>());
65    auto &beta_s =
66        *sycl::ext::oneapi::group_local_memory_for_overwrite<float[MAX_H]>(
67            sycl::ext::oneapi::this_work_item::get_work_group<3>());
68
69    const int h0 = item_ct1.get_group(1) * MAX_H;
70    const int nh = sycl::min(MAX_H, h_v - h0);
71    const int j = item_ct1.get_group(2) * JTHREADS + item_ct1.get_local_id(2);
72
73    // stage this block's q/k rows and its per-head scalars
74    for (int hi = 0; hi < nh; ++hi) {
75        const int h = h0 + hi;
76        const int src = h % h_k;                       // MODULO head pairing
77#pragma unroll
78        for (int i = item_ct1.get_local_id(2); i < S; i += JTHREADS) {
79            ks[hi][i] = k[src * S + i];
80            qs[hi][i] = q[src * S + i];
81        }
82        if (item_ct1.get_local_id(2) == 0) {
83            dec_s[hi] = sycl::native::exp(gate[h]);
84            beta_s[hi] = beta[h];
85        }
86    }
87    /*
88    DPCT1065: Consider replacing sycl::nd_item::barrier() with
89    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
90    performance if there is no access to global memory.
91    */
92    item_ct1.barrier();
93    if (j >= S) return;
94
95    for (int hi = 0; hi < nh; ++hi) {
96        const int h = h0 + hi;
97        const float dec = dec_s[hi], b = beta_s[hi];
98        float* col = state + (size_t) h * S + j;        // (S, h_v, S) with j fastest
99        const size_t stride = (size_t) h_v * S;
100
101        // pass 1: decay the state and contract it against k.  Decay BEFORE the update - PROPERTY 5.
102        float sk = 0.0f;
103        for (int i = 0; i < S; ++i) {
104            const float s = col[(size_t) i * stride] * dec;
105            col[(size_t) i * stride] = s;
106            sk += s * ks[hi][i];
107        }
108        const float d = (v[(size_t) h * S + j] - sk) * b;
109        // pass 2: the rank-1 update, then read out against q using the UPDATED state
110        float dot = 0.0f;
111        for (int i = 0; i < S; ++i) {
112            const float s = col[(size_t) i * stride] + ks[hi][i] * d;
113            col[(size_t) i * stride] = s;
114            dot += s * qs[hi][i];
115        }
116        o[(size_t) h * S + j] = dot;
117    }
118}
119
120/// `ggml_ssm_conv`: out[c] = sum_i inp[i][c] * kW[c*d_conv + i], inp = [conv_state | x], and the state slides.
121/// One thread per channel; d_conv is 4, so the serial work per thread is a 4-tap dot and an unrolled shift.
122__dpct_inline__ void gdn_conv_kernel(float *__restrict__ cs,
123                                     const float *__restrict__ x,
124                                     const float *__restrict__ kW,
125                                     float *__restrict__ out, int C, int dc) {
126    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
127    const int c = item_ct1.get_group(2) * item_ct1.get_local_range(2) +
128                  item_ct1.get_local_id(2);
129    if (c >= C) return;
130    float* st = cs + (size_t) c * (dc - 1);
131    const float* w = kW + (size_t) c * dc;
132    float acc = 0.0f;
133#pragma unroll
134    for (int i = 0; i < dc - 1; ++i) acc +=
135        st[i] * w[i]; // kernel[0] reads the OLDEST state row
136    acc += x[c] * w[dc - 1];                                // the new input lands in the LAST tap
137    out[c] = acc;
138#pragma unroll
139    for (int i = 0; i < dc - 2; ++i)
140        st[i] = st[i + 1]; // slide: drop the oldest, append the newest
141    st[dc - 2] = x[c];
142}
143
144/// `build_gdn_l2_norm`, one warp per row: x / sqrt(sum(x^2) + eps) over the last axis.
145///
146/// The sum is accumulated in DOUBLE, as `ref/gdn.py` does (`l2_norm(q.astype(np.float64), eps)`), because the
147/// reference deliberately computes this one in float64 and then casts - so matching its precision is part of
148/// transcribing it.
149__dpct_inline__ void gdn_l2_kernel(float *__restrict__ x, int cols, float eps) {
150    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
151    const int row = item_ct1.get_group(2);
152    float* p = x + (size_t) row * cols;
153    double acc = 0.0;
154#pragma unroll
155    for (int i = item_ct1.get_local_id(2); i < cols;
156         i += item_ct1.get_local_range(2)) acc += (double)p[i] * (double)p[i];
157    // warp reduction
158    /*
159DPCT1108: '__shfl_down_sync' was migrated with the experimental feature
160masked sub_group function which may not be supported by all compilers or
161runtimes. You may need to adjust the code.
162*/
163#pragma unroll
164    for (int off = 16; off > 0; off >>= 1) acc +=
165        dpct::experimental::shift_sub_group_left(
166            0xFFFFFFFFu, sycl::ext::oneapi::this_work_item::get_sub_group(),
167            acc, off);
168    auto &ssum = *sycl::ext::oneapi::group_local_memory_for_overwrite<double>(
169        sycl::ext::oneapi::this_work_item::get_work_group<3>());
170    if (item_ct1.get_local_id(2) == 0) ssum = acc;
171    /*
172    DPCT1065: Consider replacing sycl::nd_item::barrier() with
173    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
174    performance if there is no access to global memory.
175    */
176    item_ct1.barrier();
177    const float inv = (float)(1.0 / sycl::sqrt(ssum + (double)eps));
178#pragma unroll
179    for (int i = item_ct1.get_local_id(2); i < cols;
180         i += item_ct1.get_local_range(2)) p[i] *= inv;
181}
182
183/// y = rms_norm(o, eps) * ssm_norm * sigmoid(z), one warp per head, norm over that head's S values.
184__dpct_inline__ void gdn_out_norm_kernel(const float *__restrict__ o,
185                                         const float *__restrict__ z,
186                                         const float *__restrict__ ssm_norm,
187                                         float *__restrict__ y, int S,
188                                         float eps) {
189    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
190    const int h = item_ct1.get_group(2);
191    const float* po = o + (size_t) h * S;
192    const float* pz = z + (size_t) h * S;
193    float* py = y + (size_t) h * S;
194    double acc = 0.0;
195#pragma unroll
196    for (int i = item_ct1.get_local_id(2); i < S;
197         i += item_ct1.get_local_range(2)) acc += (double)po[i] * (double)po[i];
198    /*
199DPCT1108: '__shfl_down_sync' was migrated with the experimental feature
200masked sub_group function which may not be supported by all compilers or
201runtimes. You may need to adjust the code.
202*/
203#pragma unroll
204    for (int off = 16; off > 0; off >>= 1) acc +=
205        dpct::experimental::shift_sub_group_left(
206            0xFFFFFFFFu, sycl::ext::oneapi::this_work_item::get_sub_group(),
207            acc, off);
208    auto &ssum = *sycl::ext::oneapi::group_local_memory_for_overwrite<double>(
209        sycl::ext::oneapi::this_work_item::get_work_group<3>());
210    if (item_ct1.get_local_id(2) == 0) ssum = acc;
211    item_ct1.barrier(sycl::access::fence_space::local_space);
212    const float inv = (float)(1.0 / sycl::sqrt(ssum / (double)S + (double)eps));
213#pragma unroll
214    for (int i = item_ct1.get_local_id(2); i < S;
215         i += item_ct1.get_local_range(2))
216        py[i] = po[i] * inv * ssm_norm[i] * sigmoid_f(pz[i]);
217}
218
219}  // namespace
220
221void gdn_step(float *state, const float *q, const float *k, const float *v,
222              const float *gate, const float *beta, float *o,
223              const GdnShapes &s, void *stream) try {
224    if (s.S <= 0 || s.h_k <= 0 || s.h_v <= 0) return;
225    if (s.S > 128) {
226        std::fprintf(stderr, "gdn_step: S = %lld exceeds the staged 128 (`ks`/`qs` are [8][128])\n",
227                     (long long) s.S);
228        std::exit(1);
229    }
230    const dpct::dim3 grid((unsigned)((s.S + JTHREADS - 1) / JTHREADS),
231                          (unsigned)((s.h_v + MAX_H - 1) / MAX_H));
232    {
233        auto exp_props = sycl::ext::oneapi::experimental::properties{
234            sycl::ext::oneapi::experimental::use_root_sync};
235
236        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
237            ->template parallel_for<dpct_kernel_name<class gdn_step_kernel_34b62e>>(
238                sycl::nd_range<3>(grid * sycl::range(1, 1, JTHREADS),
239                                  sycl::range(1, 1, JTHREADS)),
240                exp_props, [=](sycl::nd_item<3> item_ct1) {
241                    gdn_step_kernel(state, q, k, v, gate, beta, o, (int)s.S,
242                                    (int)s.h_k, (int)s.h_v);
243                });
244    }
245    if (stream == nullptr) {
246        const dpct::err0 e = DPCT_CHECK_ERROR(
247            dpct::get_current_device().queues_wait_and_throw());
248    }
249}
250catch (sycl::exception const &exc) {
251  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
252            << ", line:" << __LINE__ << std::endl;
253  std::exit(1);
254}
255
256void gdn_conv_step(float *conv_state, const float *x, const float *kW,
257                   float *out, int64_t channels, int64_t d_conv,
258                   void *stream) try {
259    if (channels <= 0 || d_conv < 1) return;
260    const int blocks = (int) ((channels + 255) / 256);
261    {
262        auto exp_props = sycl::ext::oneapi::experimental::properties{
263            sycl::ext::oneapi::experimental::use_root_sync};
264
265        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
266            ->template parallel_for<dpct_kernel_name<class gdn_conv_kernel_b12e73>>(
267                sycl::nd_range<3>(sycl::range(1, 1, blocks) *
268                                      sycl::range(1, 1, 256),
269                                  sycl::range(1, 1, 256)),
270                exp_props, [=](sycl::nd_item<3> item_ct1) {
271                    gdn_conv_kernel(conv_state, x, kW, out, (int)channels,
272                                    (int)d_conv);
273                });
274    }
275    if (stream == nullptr) {
276        const dpct::err0 e = DPCT_CHECK_ERROR(
277            dpct::get_current_device().queues_wait_and_throw());
278    }
279}
280catch (sycl::exception const &exc) {
281  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
282            << ", line:" << __LINE__ << std::endl;
283  std::exit(1);
284}
285
286void gdn_l2_norm(float *x, int64_t rows, int64_t cols, float eps,
287                 void *stream) try {
288    if (rows <= 0 || cols <= 0) return;
289    if (cols > 1024) {
290        std::fprintf(stderr, "gdn_l2_norm: cols = %lld exceeds the 1024-wide warp reduction\n", (long long) cols);
291        std::exit(1);
292    }
293    {
294        auto exp_props = sycl::ext::oneapi::experimental::properties{
295            sycl::ext::oneapi::experimental::use_root_sync};
296        dpct::has_capability_or_fail(
297            strata::q_of(stream)->get_device(),
298            {sycl::aspect::fp64});
299
300        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
301            ->template parallel_for<dpct_kernel_name<class gdn_l2_kernel_fcfb3d>>(
302                sycl::nd_range<3>(sycl::range(1, 1, (unsigned)rows) *
303                                      sycl::range(1, 1, 32),
304                                  sycl::range(1, 1, 32)),
305                exp_props,
306                [=](sycl::nd_item<3> item_ct1)
307                    [[sycl::reqd_sub_group_size(32)]] {
308                        gdn_l2_kernel(x, (int)cols, eps);
309                    });
310    }
311    if (stream == nullptr) {
312        const dpct::err0 e = DPCT_CHECK_ERROR(
313            dpct::get_current_device().queues_wait_and_throw());
314    }
315}
316catch (sycl::exception const &exc) {
317  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
318            << ", line:" << __LINE__ << std::endl;
319  std::exit(1);
320}
321
322/// `beta = sigmoid(beta)`, in place, over the `h_v` per-head scalars.
323///
324/// **THIS IS `build_layer_attn_linear` L889, AND LEAVING IT OUT WAS THE C1 BUG.**  The reference computes
325/// `beta = ggml_sigmoid(ssm_beta @ cur)` and hands the RESULT to the delta net; `gdn_step_kernel` is documented
326/// as `d[h,j] = (v[h,j] - sk[h,j]) * beta[h]` and applies no sigmoid of its own, so the layer glue owes it one.
327/// The engine passed the raw pre-activation, which is unbounded and signed - the delta-net write strength then
328/// stops being a fraction and the whole recurrence is wrong from layer 0.
329///
330/// **IT SURVIVED `gdn_parity` BECAUSE THAT TEST SUPPLIES ITS OWN `beta`.**  The kernel was always right; only
331/// the glue between the projection and the kernel was wrong, and `ref/gdn.py` (`beta = sigmoid(wbeta @ x)`) and
332/// `ref/model.py` (`beta = G.sigmoid(proj(...))`) both get it right - so the two transcriptions agreed with
333/// each other and neither was ever compared against the C++ that actually runs.
334__dpct_inline__ void gdn_beta_gate_kernel(float *__restrict__ beta, int n) {
335    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
336    const int i = item_ct1.get_group(2) * item_ct1.get_local_range(2) +
337                  item_ct1.get_local_id(2);
338    if (i < n) beta[i] = sigmoid_f(beta[i]);
339}
340
341void gdn_beta_gate(float *beta, int64_t h_v, void *stream) try {
342    if (beta == nullptr || h_v <= 0) return;
343    const int n = (int) h_v;
344    {
345        auto exp_props = sycl::ext::oneapi::experimental::properties{
346            sycl::ext::oneapi::experimental::use_root_sync};
347
348        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
349            ->template parallel_for<dpct_kernel_name<class gdn_beta_gate_kernel_e2ab3e>>(
350                sycl::nd_range<3>(
351                    sycl::range(1, 1, (unsigned)((n + 127) / 128)) *
352                        sycl::range(1, 1, 128),
353                    sycl::range(1, 1, 128)),
354                exp_props, [=](sycl::nd_item<3> item_ct1) {
355                    gdn_beta_gate_kernel(beta, n);
356                });
357    }
358    if (stream == nullptr) {
359        const dpct::err0 e = DPCT_CHECK_ERROR(
360            dpct::get_current_device().queues_wait_and_throw());
361    }
362}
363catch (sycl::exception const &exc) {
364  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
365            << ", line:" << __LINE__ << std::endl;
366  std::exit(1);
367}
368
369void gdn_out_norm(const float *o, const float *z, const float *ssm_norm,
370                  float *y, int64_t h_v, int64_t S, float eps,
371                  void *stream) try {
372    if (h_v <= 0 || S <= 0) return;
373    {
374        auto exp_props = sycl::ext::oneapi::experimental::properties{
375            sycl::ext::oneapi::experimental::use_root_sync};
376        dpct::has_capability_or_fail(
377            strata::q_of(stream)->get_device(),
378            {sycl::aspect::fp64});
379
380        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
381            ->template parallel_for<dpct_kernel_name<class gdn_out_norm_kernel_9883e0>>(
382                sycl::nd_range<3>(sycl::range(1, 1, (unsigned)h_v) *
383                                      sycl::range(1, 1, 32),
384                                  sycl::range(1, 1, 32)),
385                exp_props,
386                [=](sycl::nd_item<3> item_ct1)
387                    [[sycl::reqd_sub_group_size(32)]] {
388                        gdn_out_norm_kernel(o, z, ssm_norm, y, (int)S, eps);
389                    });
390    }
391    if (stream == nullptr) {
392        const dpct::err0 e = DPCT_CHECK_ERROR(
393            dpct::get_current_device().queues_wait_and_throw());
394    }
395}
396catch (sycl::exception const &exc) {
397  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
398            << ", line:" << __LINE__ << std::endl;
399  std::exit(1);
400}
401
402}  // namespace strata::kernels