okami.mom/strata

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

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

main
14.9 KiB341 linesraw
1// src/kernels/cuda/fused_gdn.cu - see include/strata/kernels/fused_gdn.hpp.
2#define DPCT_PROFILING_ENABLED
3#include <sycl/sycl.hpp>
4#include "strata/kprof.hpp"
5#include "strata/core/geometry.hpp"
6#include <dpct/dpct.hpp>
7#include "strata/sycl_queue.hpp"
8#include "strata/kernels/fused_gdn.hpp"
9
10#include <cstdio>
11#include <cstdlib>
12
13namespace strata::kernels {
14namespace {
15
16constexpr int S = 128;          // state size (rows = cols = 128)
17static_assert(S == strata::core::kCompiledGeometry.ssm_state_size, "fused_gdn is compiled for core/geometry.hpp");
18constexpr int RG = 4;           // row groups
19constexpr int RPG = S / RG;     // 32 rows per thread
20
21/*
22DPCT1110: The total declared local variable size in device function
23gdn_step_norm_kernel exceeds 128 bytes and may cause high register pressure.
24Consult with your hardware vendor to find the total register size available and
25adjust the code, or use smaller sub-group size to avoid high register pressure.
26*/
27__dpct_inline__ void gdn_step_norm_kernel(
28    float *__restrict__ state, const float *__restrict__ q,
29    const float *__restrict__ k, const float *__restrict__ v,
30    const float *__restrict__ gate, const float *__restrict__ beta,
31    const float *__restrict__ z, const float *__restrict__ gamma, float eps,
32    float *__restrict__ y, int h_k, int h_v) {
33    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
34auto &sk = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[S]>(
35    sycl::ext::oneapi::this_work_item::get_work_group<3>());
36    auto &sq = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[S]>(
37        sycl::ext::oneapi::this_work_item::get_work_group<3>());
38    auto &red_kv =
39        *sycl::ext::oneapi::group_local_memory_for_overwrite<float[RG][S]>(
40            sycl::ext::oneapi::this_work_item::get_work_group<3>());
41    auto &red_o =
42        *sycl::ext::oneapi::group_local_memory_for_overwrite<float[RG][S]>(
43            sycl::ext::oneapi::this_work_item::get_work_group<3>());
44    auto &wsum = *sycl::ext::oneapi::group_local_memory_for_overwrite<
45        float[S * RG / 32]>(
46        sycl::ext::oneapi::this_work_item::get_work_group<3>());
47    const int head = item_ct1.get_group(2);
48    const int col = item_ct1.get_local_id(2); // 0..127
49    const int rg = item_ct1.get_local_id(1);  // 0..3
50    const int tid = rg * S + col;
51    const int qh = head % h_k;
52    if (tid < S) { sk[tid] = k[qh * S + tid]; sq[tid] = q[qh * S + tid]; }
53    float s[RPG];
54    float* base = state + ((size_t) (rg * RPG) * h_v + head) * S + col;
55    const size_t row_stride = (size_t) h_v * S;
56#pragma unroll
57    for (int r = 0; r < RPG; ++r) s[r] = base[r * row_stride];
58    /*
59    DPCT1065: Consider replacing sycl::nd_item::barrier() with
60    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
61    performance if there is no access to global memory.
62    */
63    item_ct1.barrier();
64    const float g = sycl::native::exp(gate[head]);
65    float kv = 0.0f;
66#pragma unroll
67    for (int r = 0; r < RPG; ++r) kv = sycl::fma(s[r], sk[rg * RPG + r], kv);
68    red_kv[rg][col] = kv;
69    /*
70    DPCT1065: Consider replacing sycl::nd_item::barrier() with
71    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
72    performance if there is no access to global memory.
73    */
74    item_ct1.barrier();
75    const float kv_col = red_kv[0][col] + red_kv[1][col] + red_kv[2][col] + red_kv[3][col];
76    const float delta = (v[head * S + col] - g * kv_col) * beta[head];
77    float o = 0.0f;
78#pragma unroll
79    for (int r = 0; r < RPG; ++r) {
80        s[r] = sycl::fma((float)g, s[r], sk[rg * RPG + r] * delta);
81        o = sycl::fma(s[r], sq[rg * RPG + r], o);
82        base[r * row_stride] = s[r];
83    }
84    red_o[rg][col] = o;
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    item_ct1.barrier();
91    float oc = 0.0f, sq_part = 0.0f;
92    if (rg == 0) {
93        oc = (red_o[0][col] + red_o[1][col] + red_o[2][col] + red_o[3][col]) *
94             sycl::rsqrt((float)S);
95        sq_part = oc * oc;
96    }
97    // RMS over the head's 128 outputs: warps of row group 0 are threads 0..127.
98    /*
99DPCT1108: '__shfl_xor_sync' was migrated with the experimental feature masked
100sub_group function which may not be supported by all compilers or runtimes. You
101may need to adjust the code.
102*/
103#pragma unroll
104    for (int o2 = 16; o2 > 0; o2 >>= 1) sq_part +=
105        dpct::experimental::permute_sub_group_by_xor(
106            0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),
107            sq_part, o2);
108    if ((tid & 31) == 0) wsum[tid >> 5] = sq_part;
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    if (rg == 0) {
116        const float ss = wsum[0] + wsum[1] + wsum[2] + wsum[3];
117        const float scale = sycl::rsqrt(ss / (float)S + eps);
118        const float zz = z[head * S + col];
119        y[head * S + col] =
120            oc * scale * gamma[col] * (1.0f / (1.0f + sycl::native::exp(-zz)));
121    }
122}
123
124__dpct_inline__ void gdn_conv_l2_kernel(float *__restrict__ hist,
125                                        const float *__restrict__ qkv,
126                                        const float *__restrict__ w,
127                                        float *__restrict__ h, int qk_heads,
128                                        float eps) {
129    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
130auto &part =
131    *sycl::ext::oneapi::group_local_memory_for_overwrite<float[S / 32]>(
132        sycl::ext::oneapi::this_work_item::get_work_group<3>());
133    const int c = item_ct1.get_group(2) * S + item_ct1.get_local_id(2);
134    const float v0 = hist[c * 3], v1 = hist[c * 3 + 1], v2 = hist[c * 3 + 2], x = qkv[c];
135    float sum = v0 * w[c * 4] + v1 * w[c * 4 + 1] + v2 * w[c * 4 + 2] + x * w[c * 4 + 3];
136    hist[c * 3] = v1;
137    hist[c * 3 + 1] = v2;
138    hist[c * 3 + 2] = x;
139    float y = sum / (1.0f + sycl::native::exp(-sum));
140    if ((int)item_ct1.get_group(2) < qk_heads) {
141        float sq = y * y;
142        /*
143DPCT1108: '__shfl_xor_sync' was migrated with the experimental feature masked
144sub_group function which may not be supported by all compilers or runtimes. You
145may need to adjust the code.
146*/
147#pragma unroll
148        for (int o = 16; o > 0; o >>= 1) sq +=
149            dpct::experimental::permute_sub_group_by_xor(
150                0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),
151                sq, o);
152        if ((item_ct1.get_local_id(2) & 31) == 0)
153            part[item_ct1.get_local_id(2) >> 5] = sq;
154        /*
155        DPCT1118: SYCL group functions and algorithms must be encountered in
156        converged control flow. You may need to adjust the code.
157        */
158        /*
159        DPCT1065: Consider replacing sycl::nd_item::barrier() with
160        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
161        better performance if there is no access to global memory.
162        */
163        item_ct1.barrier();
164        const float ss = part[0] + part[1] + part[2] + part[3];
165        y *= sycl::rsqrt(ss + eps);
166    }
167    h[c] = y;
168}
169
170__dpct_inline__ void
171gdn_ab_kernel(const float *__restrict__ x, const uint16_t *__restrict__ wa,
172              const uint16_t *__restrict__ wb, const float *__restrict__ dt,
173              const float *__restrict__ ssm_a, float *__restrict__ gate,
174              float *__restrict__ beta, int n, int h_v) {
175    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
176    const int row = item_ct1.get_group(2) * 8 + (item_ct1.get_local_id(2) >> 5),
177              lane = item_ct1.get_local_id(2) & 31;
178    if (row >= 2 * h_v) return;
179    const bool is_beta = row >= h_v;
180    const int r = is_beta ? row - h_v : row;
181    const sycl::uint4 *w4 = reinterpret_cast<const sycl::uint4 *>(
182        (is_beta ? wb : wa) + (size_t)r * n);
183    float acc = 0.0f;
184    for (int j = lane; j < n / 8; j += 32) {
185        /*
186        DPCT1098: The '*' expression is used instead of the __ldg call.
187        These two expressions do not provide the exact same functionality. Check
188        the generated code for potential precision and/or performance issues.
189        */
190        const sycl::uint4 wv = *(w4 + j);
191        const sycl::float4 xa =
192            *reinterpret_cast<const sycl::float4 *>(x + j * 8);
193        const sycl::float4 xb =
194            *reinterpret_cast<const sycl::float4 *>(x + j * 8 + 4);
195        acc = sycl::fma(sycl::bit_cast<float>(wv.x() << 16), (float)(xa.x()),
196                        acc);
197            acc = sycl::fma(sycl::bit_cast<float>(wv.x() & 0xffff0000u),
198                            (float)(xa.y()), acc);
199        acc = sycl::fma(sycl::bit_cast<float>(wv.y() << 16), (float)(xa.z()),
200                        acc);
201            acc = sycl::fma(sycl::bit_cast<float>(wv.y() & 0xffff0000u),
202                            (float)(xa.w()), acc);
203        acc = sycl::fma(sycl::bit_cast<float>(wv.z() << 16), (float)(xb.x()),
204                        acc);
205            acc = sycl::fma(sycl::bit_cast<float>(wv.z() & 0xffff0000u),
206                            (float)(xb.y()), acc);
207        acc = sycl::fma(sycl::bit_cast<float>(wv.w() << 16), (float)(xb.z()),
208                        acc);
209            acc = sycl::fma(sycl::bit_cast<float>(wv.w() & 0xffff0000u),
210                            (float)(xb.w()), acc);
211    }
212    /*
213DPCT1108: '__shfl_xor_sync' was migrated with the experimental feature masked
214sub_group function which may not be supported by all compilers or runtimes. You
215may need to adjust the code.
216*/
217#pragma unroll
218    for (int o = 16; o > 0; o >>= 1) acc +=
219        dpct::experimental::permute_sub_group_by_xor(
220            0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),
221            acc, o);
222    if (lane != 0) return;
223    if (is_beta) {
224        beta[r] = 1.0f / (1.0f + sycl::native::exp(-acc));
225    } else {
226        const float v = acc + dt[r];
227        const float sp = v > 20.0f ? v : sycl::log1p(sycl::native::exp(v));
228        gate[r] = sp * ssm_a[r];
229    }
230}
231
232}  // namespace
233
234void fused_gdn_conv_l2(float* history, const float* qkv, const float* conv_w, float* h, int channels, int qk_heads,
235                       float eps, void* stream) {
236    if (!history || !qkv || !conv_w || !h || channels % S != 0 || qk_heads < 0 || qk_heads > channels / S) {
237        std::fprintf(stderr, "fused_gdn_conv_l2: invalid arguments\n");
238        std::exit(1);
239    }
240    {
241        auto exp_props = sycl::ext::oneapi::experimental::properties{
242            sycl::ext::oneapi::experimental::use_root_sync};
243
244        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
245            ->template parallel_for<dpct_kernel_name<class gdn_conv_l2_kernel_44cd0c>>(
246                sycl::nd_range<3>(sycl::range(1, 1, (unsigned)(channels / S)) *
247                                      sycl::range(1, 1, S),
248                                  sycl::range(1, 1, S)),
249                exp_props,
250                [=](sycl::nd_item<3> item_ct1)
251                    [[sycl::reqd_sub_group_size(32)]] {
252                        gdn_conv_l2_kernel(history, qkv, conv_w, h, qk_heads,
253                                           eps);
254                    });
255    }
256    /*
257    DPCT1010: SYCL uses exceptions to report errors and does not use the
258    error codes. The cudaGetLastError function call was replaced with 0. You
259    need to rewrite this code.
260    */
261    const dpct::err0 e = 0;
262    /*
263    DPCT1009: SYCL reports errors using exceptions and does not use error
264    codes. Please replace the "get_error_string_dummy(...)" with a real
265    error-handling function.
266    */
267}
268
269void fused_gdn_ab(const float* x, const uint16_t* w_alpha, const uint16_t* w_beta, const float* dt, const float* ssm_a,
270                  float* gate, float* beta, int n_embd, int h_v, void* stream) {
271    if (!x || !w_alpha || !w_beta || !dt || !ssm_a || !gate || !beta || n_embd % 8 != 0 || h_v <= 0) {
272        std::fprintf(stderr, "fused_gdn_ab: invalid arguments\n");
273        std::exit(1);
274    }
275    {
276        auto exp_props = sycl::ext::oneapi::experimental::properties{
277            sycl::ext::oneapi::experimental::use_root_sync};
278
279        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
280            ->template parallel_for<dpct_kernel_name<class gdn_ab_kernel_c211b9>>(
281                sycl::nd_range<3>(
282                    sycl::range(1, 1, (unsigned)((2 * h_v + 7) / 8)) *
283                        sycl::range(1, 1, 256),
284                    sycl::range(1, 1, 256)),
285                exp_props,
286                [=](sycl::nd_item<3> item_ct1)
287                    [[sycl::reqd_sub_group_size(32)]] {
288                        gdn_ab_kernel(x, w_alpha, w_beta, dt, ssm_a, gate, beta,
289                                      n_embd, h_v);
290                    });
291    }
292    /*
293    DPCT1010: SYCL uses exceptions to report errors and does not use the
294    error codes. The cudaGetLastError function call was replaced with 0. You
295    need to rewrite this code.
296    */
297    const dpct::err0 e = 0;
298    /*
299    DPCT1009: SYCL reports errors using exceptions and does not use error
300    codes. Please replace the "get_error_string_dummy(...)" with a real
301    error-handling function.
302    */
303}
304
305void fused_gdn_step_norm(float* state, const float* q, const float* k, const float* v, const float* gate,
306                         const float* beta, const float* z, const float* gamma, float eps, float* y, int h_k, int h_v,
307                         void* stream) {
308    if (!state || !q || !k || !v || !gate || !beta || !z || !gamma || !y || h_k <= 0 || h_v <= 0 || h_v % h_k) {
309        std::fprintf(stderr, "fused_gdn_step_norm: invalid arguments\n");
310        std::exit(1);
311    }
312    /*
313    DPCT1049: The work-group size passed to the SYCL kernel may exceed the
314    limit. To get the device limit, query info::device::max_work_group_size.
315    Adjust the work-group size if needed.
316    */
317    {
318        auto exp_props = sycl::ext::oneapi::experimental::properties{
319            sycl::ext::oneapi::experimental::use_root_sync};
320
321        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
322            ->template parallel_for<dpct_kernel_name<class gdn_step_norm_kernel_51bed3>>(
323                sycl::nd_range<3>(sycl::range(1, 1, (unsigned)h_v) *
324                                      sycl::range(1, RG, S),
325                                  sycl::range(1, RG, S)),
326                exp_props,
327                [=](sycl::nd_item<3> item_ct1)
328                    [[sycl::reqd_sub_group_size(32)]] {
329                        gdn_step_norm_kernel(state, q, k, v, gate, beta, z,
330                                             gamma, eps, y, h_k, h_v);
331                    });
332    }
333    /*
334    DPCT1010: SYCL uses exceptions to report errors and does not use the
335    error codes. The cudaGetLastError function call was replaced with 0. You
336    need to rewrite this code.
337    */
338    const dpct::err0 e = 0;
339}
340
341}  // namespace strata::kernels