okami.mom/strata

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

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

main
15.7 KiB359 linesraw
1// Adapted from llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d:
2// ggml/src/ggml-cuda/{norm.cu,common.cuh,unary.cu,unary.cuh,ssm-conv.cu,scale.cu}.
3// Compile with --use_fast_math, as the pinned backend does.
4//
5// MIT License
6// Copyright (c) 2023-2026 The ggml authors
7//
8// Permission is hereby granted, free of charge, to any person obtaining a copy
9// of this software and associated documentation files (the "Software"), to deal
10// in the Software without restriction, including without limitation the rights
11// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12// copies of the Software, and to permit persons to whom the Software is
13// furnished to do so, subject to the following conditions:
14//
15// The above copyright notice and this permission notice shall be included in all
16// copies or substantial portions of the Software.
17//
18// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24// SOFTWARE.
25#define DPCT_PROFILING_ENABLED
26#include <sycl/sycl.hpp>
27#include "strata/kprof.hpp"
28#include <dpct/dpct.hpp>
29#include "strata/sycl_queue.hpp"
30#include "strata/kernels/native_gdn_preprocess.hpp"
31#include <cmath>
32#include <cstddef>
33#include <cstdint>
34#include <initializer_list>
35#include <stdexcept>
36
37namespace strata::kernels {
38namespace {
39constexpr int S = 128;
40
41__dpct_inline__ float warp_sum(float value) {
42#pragma unroll
43    for (int offset = 16; offset > 0; offset >>= 1)
44        /*
45        DPCT1108: '__shfl_xor_sync' was migrated with the experimental
46        feature masked sub_group function which may not be supported by all
47        compilers or runtimes. You may need to adjust the code.
48        */
49        value += dpct::experimental::permute_sub_group_by_xor(
50            0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),
51            value, offset);
52    return value;
53}
54__dpct_inline__ float norm_sum(float value, float *sums) {
55    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
56    const int lane = item_ct1.get_local_id(2) % 32;
57    value = warp_sum(value);
58    if (lane == 0) sums[item_ct1.get_local_id(2) / 32] = value;
59    /*
60    DPCT1065: Consider replacing sycl::nd_item::barrier() with
61    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
62    performance if there is no access to global memory.
63    */
64    item_ct1.barrier();
65    value = lane < 8 ? sums[lane] : 0.0f;
66    return warp_sum(value);
67}
68__dpct_inline__ float sigmoid(float value) {
69    return 1.0f / (1.0f + sycl::native::exp(-value));
70}
71
72__dpct_inline__ void conv_silu(float *__restrict__ history,
73                               const float *__restrict__ input,
74                               const float *__restrict__ weights,
75                               float *__restrict__ raw_output,
76                               float *__restrict__ silu_output, int channels) {
77    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
78    const int c = item_ct1.get_group(2) * item_ct1.get_local_range(2) +
79                  item_ct1.get_local_id(2);
80    if (c >= channels) return;
81    float values[4] = {history[c * 3], history[c * 3 + 1], history[c * 3 + 2], input[c]};
82    float sum = 0.0f;
83#pragma unroll
84    for (int tap = 0; tap < 4; ++tap) sum += values[tap] * weights[c * 4 + tap];
85    // The native SSM kernel adds its zero bias even when there is no bias input.
86    /*
87    DPCT1013: The rounding mode could not be specified and the generated
88    code may have different accuracy than the original code. Verify the
89    correctness. SYCL math built-in function rounding mode is aligned with
90    OpenCL C 1.2 standard.
91    */
92    sum = sum + 0.0f;
93    raw_output[c] = sum;
94    silu_output[c] = sum / (1.0f + sycl::native::exp(-sum));
95#pragma unroll
96    for (int tap = 0; tap < 3; ++tap) history[c * 3 + tap] = values[tap + 1];
97}
98
99__dpct_inline__ void l2_norm(float *input, float epsilon, float scale_after) {
100    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
101    const int col = item_ct1.get_local_id(2);
102    input += size_t(item_ct1.get_group(2)) * S;
103    const float value = col < S ? input[col] : 0.0f;
104    float partial = 0.0f;
105    if (col < S) partial += value * value;
106    auto &sums =
107        *sycl::ext::oneapi::group_local_memory_for_overwrite<float[32]>(
108            sycl::ext::oneapi::this_work_item::get_work_group<3>());
109    partial = norm_sum(partial, sums);
110    const float scale = sycl::rsqrt(partial / S + epsilon);
111    if (col < S) {
112        // Preserve the FP32 store boundary between RMSNorm and ggml_scale.
113        /*
114        DPCT1013: The rounding mode could not be specified and the generated
115        code may have different accuracy than the original code. Verify the
116        correctness. SYCL math built-in function rounding mode is aligned with
117        OpenCL C 1.2 standard.
118        */
119        const float normalized = scale * value;
120        /*
121        DPCT1013: The rounding mode could not be specified and the generated
122        code may have different accuracy than the original code. Verify the
123        correctness. SYCL math built-in function rounding mode is aligned with
124        OpenCL C 1.2 standard.
125        */
126        input[col] = sycl::fma(normalized, scale_after, 0.0f);
127    }
128}
129
130__dpct_inline__ void beta_sigmoid(float *beta, int count) {
131    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
132    const int i = item_ct1.get_group(2) * item_ct1.get_local_range(2) +
133                  item_ct1.get_local_id(2);
134    if (i < count) beta[i] = sigmoid(beta[i]);
135}
136__dpct_inline__ void gate_softplus(const float *__restrict__ alpha,
137                                   const float *__restrict__ dt,
138                                   const float *__restrict__ ssm_a,
139                                   float *__restrict__ gate, int count) {
140    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
141    const int i = item_ct1.get_group(2) * item_ct1.get_local_range(2) +
142                  item_ct1.get_local_id(2);
143    if (i >= count) return;
144    /*
145    DPCT1013: The rounding mode could not be specified and the generated
146    code may have different accuracy than the original code. Verify the
147    correctness. SYCL math built-in function rounding mode is aligned with
148    OpenCL C 1.2 standard.
149    */
150    const float value = alpha[i] + dt[i];
151    const float softplus = value > 20.0f
152                               ? value
153                               : sycl::log1p(sycl::native::exp(
154                                     value)); // 1 + e^v loses e^v below ~1e-7
155    gate[i] = softplus * ssm_a[i];
156}
157
158__dpct_inline__ void out_norm(const float *__restrict__ input,
159                              const float *__restrict__ z,
160                              const float *__restrict__ gamma,
161                              float *__restrict__ output, float epsilon) {
162    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
163    const int col = item_ct1.get_local_id(2);
164    const size_t offset = size_t(item_ct1.get_group(2)) * S;
165    const float value = col < S ? input[offset + col] : 0.0f;
166    float partial = 0.0f;
167    if (col < S) partial += value * value;
168    auto &sums =
169        *sycl::ext::oneapi::group_local_memory_for_overwrite<float[32]>(
170            sycl::ext::oneapi::this_work_item::get_work_group<3>());
171    partial = norm_sum(partial, sums);
172    const float scale = sycl::rsqrt(partial / S + epsilon);
173    if (col < S) {
174        // RMSNorm+gamma is one pinned fused operator, followed by sigmoid*mul.
175        /*
176        DPCT1013: The rounding mode could not be specified and the generated
177        code may have different accuracy than the original code. Verify the
178        correctness. SYCL math built-in function rounding mode is aligned with
179        OpenCL C 1.2 standard.
180        */
181        const float weighted = scale * value * gamma[col];
182        output[offset + col] = weighted * sigmoid(z[offset + col]);
183    }
184}
185
186struct Span { const void* pointer; size_t bytes; };
187void valid(Span span) {
188    const auto address = reinterpret_cast<uintptr_t>(span.pointer);
189    if (!span.pointer || address % sizeof(float) || span.bytes > UINTPTR_MAX - address)
190        throw std::invalid_argument("native GDN preprocessing requires aligned nonnull valid spans");
191}
192void disjoint(Span a, Span b) {
193    const auto ap = reinterpret_cast<uintptr_t>(a.pointer), bp = reinterpret_cast<uintptr_t>(b.pointer);
194    if (ap < bp + b.bytes && bp < ap + a.bytes)
195        throw std::invalid_argument("native GDN preprocessing requires disjoint writable spans");
196}
197void count_and_stream(int64_t count, void* stream) {
198    if (!stream || count <= 0 || count > 65535)
199        throw std::invalid_argument("native GDN preprocessing requires a stream and count in [1,65535]");
200}
201void norm_geometry(int64_t rows, int64_t cols, float epsilon, void* stream) {
202    count_and_stream(rows, stream);
203    if (cols != S || !std::isfinite(epsilon) || epsilon < 0.0f)
204        throw std::invalid_argument("native GDN norm requires width 128 and finite nonnegative epsilon");
205}
206void check_launch() {
207    /*
208    DPCT1010: SYCL uses exceptions to report errors and does not use the
209    error codes. The cudaGetLastError function call was replaced with 0. You
210    need to rewrite this code.
211    */
212    const auto error = 0;
213    /*
214    DPCT1009: SYCL reports errors using exceptions and does not use error
215    codes. Please replace the "get_error_string_dummy(...)" with a real
216    error-handling function.
217    */
218    /*
219    DPCT1001: The statement could not be removed.
220    */
221    /*
222    DPCT1000: Error handling if-stmt was detected but could not be
223    rewritten.
224    */
225    if (error !=
226        0) throw std::runtime_error(dpct::get_error_string_dummy(error));
227}
228}
229
230void native_gdn_conv_silu(float* history, const float* input, const float* weights,
231                          float* raw_output, float* silu_output, int64_t channels,
232                          int64_t d_conv, void* stream) {
233    count_and_stream(channels, stream);
234    if (d_conv != 4) throw std::invalid_argument("native GDN convolution requires four taps");
235    const size_t bytes = size_t(channels) * sizeof(float);
236    const Span writable[] = {{history, 3 * bytes}, {raw_output, bytes}, {silu_output, bytes}};
237    const Span inputs[] = {{input, bytes}, {weights, 4 * bytes}};
238    for (auto span : writable) valid(span);
239    for (auto span : inputs) valid(span);
240    for (int i = 0; i < 3; ++i) {
241        for (int j = 0; j < i; ++j) disjoint(writable[i], writable[j]);
242        for (auto span : inputs) disjoint(writable[i], span);
243    }
244    {
245        auto exp_props = sycl::ext::oneapi::experimental::properties{
246            sycl::ext::oneapi::experimental::use_root_sync};
247
248        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
249            ->template parallel_for<dpct_kernel_name<class conv_silu_1ba4e6>>(
250                sycl::nd_range<3>(
251                    sycl::range(1, 1, unsigned((channels + 255) / 256)) *
252                        sycl::range(1, 1, 256),
253                    sycl::range(1, 1, 256)),
254                exp_props, [=](sycl::nd_item<3> item_ct1) {
255                    conv_silu(history, input, weights, raw_output, silu_output,
256                              int(channels));
257                });
258    }
259    check_launch();
260}
261void native_gdn_l2_norm(float* input, int64_t rows, int64_t cols, float epsilon, void* stream) {
262    norm_geometry(rows, cols, epsilon, stream);
263    valid({input, size_t(rows) * S * sizeof(float)});
264    {
265        auto exp_props = sycl::ext::oneapi::experimental::properties{
266            sycl::ext::oneapi::experimental::use_root_sync};
267
268        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
269            ->submit([&](sycl::handler &cgh) {
270                auto epsilon_S_ct1 = epsilon / S;
271                auto sqrtf_float_S_ct2 = 1.0f / sqrtf(float(S));
272
273                cgh.parallel_for<dpct_kernel_name<class l2_norm_bcf2af>>(
274                    sycl::nd_range<3>(sycl::range(1, 1, unsigned(rows)) *
275                                          sycl::range(1, 1, 256),
276                                      sycl::range(1, 1, 256)),
277                    exp_props,
278                    [=](sycl::nd_item<3> item_ct1)
279                        [[sycl::reqd_sub_group_size(32)]] {
280                            l2_norm(input, epsilon_S_ct1, sqrtf_float_S_ct2);
281                        });
282            });
283    }
284    check_launch();
285}
286void native_gdn_beta_gate(float* beta, int64_t heads, void* stream) {
287    count_and_stream(heads, stream);
288    valid({beta, size_t(heads) * sizeof(float)});
289    {
290        auto exp_props = sycl::ext::oneapi::experimental::properties{
291            sycl::ext::oneapi::experimental::use_root_sync};
292
293        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
294            ->template parallel_for<dpct_kernel_name<class beta_sigmoid_fcf68f>>(
295                sycl::nd_range<3>(
296                    sycl::range(1, 1, unsigned((heads + 255) / 256)) *
297                        sycl::range(1, 1, 256),
298                    sycl::range(1, 1, 256)),
299                exp_props, [=](sycl::nd_item<3> item_ct1) {
300                    beta_sigmoid(beta, int(heads));
301                });
302    }
303    check_launch();
304}
305void native_gdn_gate(const float* alpha, const float* dt, const float* ssm_a,
306                     float* gate, int64_t heads, void* stream) {
307    count_and_stream(heads, stream);
308    const size_t bytes = size_t(heads) * sizeof(float);
309    const Span output{gate, bytes};
310    valid(output);
311    for (auto input : {Span{alpha, bytes}, Span{dt, bytes}, Span{ssm_a, bytes}}) {
312        valid(input);
313        disjoint(output, input);
314    }
315    {
316        auto exp_props = sycl::ext::oneapi::experimental::properties{
317            sycl::ext::oneapi::experimental::use_root_sync};
318
319        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
320            ->template parallel_for<dpct_kernel_name<class gate_softplus_a95cee>>(
321                sycl::nd_range<3>(
322                    sycl::range(1, 1, unsigned((heads + 255) / 256)) *
323                        sycl::range(1, 1, 256),
324                    sycl::range(1, 1, 256)),
325                exp_props, [=](sycl::nd_item<3> item_ct1) {
326                    gate_softplus(alpha, dt, ssm_a, gate, int(heads));
327                });
328    }
329    check_launch();
330}
331void native_gdn_out_norm(const float* output, const float* z, const float* gamma,
332                         float* destination, int64_t heads, int64_t cols,
333                         float epsilon, void* stream) {
334    norm_geometry(heads, cols, epsilon, stream);
335    const size_t bytes = size_t(heads) * S * sizeof(float);
336    const Span writable{destination, bytes};
337    valid(writable);
338    for (auto input : {Span{output, bytes}, Span{z, bytes}, Span{gamma, S * sizeof(float)}}) {
339        valid(input);
340        disjoint(writable, input);
341    }
342    {
343        auto exp_props = sycl::ext::oneapi::experimental::properties{
344            sycl::ext::oneapi::experimental::use_root_sync};
345
346        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
347            ->template parallel_for<dpct_kernel_name<class out_norm_a49e35>>(
348                sycl::nd_range<3>(sycl::range(1, 1, unsigned(heads)) *
349                                      sycl::range(1, 1, 256),
350                                  sycl::range(1, 1, 256)),
351                exp_props,
352                [=](sycl::nd_item<3> item_ct1)
353                    [[sycl::reqd_sub_group_size(32)]] {
354                        out_norm(output, z, gamma, destination, epsilon);
355                    });
356    }
357    check_launch();
358}
359} // namespace strata::kernels