okami.mom/strata

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

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

main
11.8 KiB268 linesraw
1// Adapted from llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d:
2// ggml/src/ggml-cuda/{dsv4-hc.cu,scale.cu,unary.cu,unary.cuh}.
3//
4// MIT License
5// Copyright (c) 2023-2026 The ggml authors
6//
7// Permission is hereby granted, free of charge, to any person obtaining a copy
8// of this software and associated documentation files (the "Software"), to deal
9// in the Software without restriction, including without limitation the rights
10// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11// copies of the Software, and to permit persons to whom the Software is
12// furnished to do so, subject to the following conditions:
13//
14// The above copyright notice and this permission notice shall be included in all
15// copies or substantial portions of the Software.
16//
17// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23// SOFTWARE.
24
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_gr_postops.hpp"
31#include <cstddef>
32#include <cstdint>
33#include <limits>
34#include <stdexcept>
35#include <string>
36#include <cmath>
37
38namespace strata::kernels {
39namespace {
40constexpr int THREADS = 256;
41__dpct_inline__ float sigmoid(float x) {
42    return 1.0f / (1.0f + sycl::native::exp(-x));
43}
44// ggml SCALE uses scale*x+bias, including its +0 bias. Retain this operation
45// explicitly so compile-time zero does not change signed-zero behavior.
46__dpct_inline__ float scale_zero_bias(float x, float scale) {
47    /*
48    DPCT1013: The rounding mode could not be specified and the generated
49    code may have different accuracy than the original code. Verify the
50    correctness. SYCL math built-in function rounding mode is aligned with
51    OpenCL C 1.2 standard.
52    */
53    return sycl::fma(scale, x, 0.0f);
54}
55__dpct_inline__ void down_silu(float *lo, int count, float scale) {
56    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
57    const std::size_t i =
58        std::size_t(item_ct1.get_group(2)) * item_ct1.get_local_range(2) +
59        item_ct1.get_local_id(2);
60    if (i >= std::size_t(count)) return;
61    const float x = scale_zero_bias(lo[i], scale);
62    lo[i] = x / (1.0f + sycl::native::exp(-x));
63}
64template <bool Fused>
65__dpct_inline__ void
66pre_gated(const float *__restrict__ xn, float *__restrict__ gate,
67          float *__restrict__ mixed, int n_embd, int hc, float scale) {
68    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
69    const std::size_t d =
70        std::size_t(item_ct1.get_group(2)) * item_ct1.get_local_range(2) +
71        item_ct1.get_local_id(2);
72    if (d >= std::size_t(n_embd)) return;
73    const std::size_t t = item_ct1.get_group(1);
74    xn += t * std::size_t(n_embd) * hc;
75    gate += t * std::size_t(n_embd) * hc;
76    mixed += t * std::size_t(n_embd);
77    float sum = 0.0f;
78    for (int c = 0; c < hc; ++c) {
79        const std::size_t i = std::size_t(c) * n_embd + d;
80        const float x = xn[i], w = sigmoid(gate[i]);
81        /*
82        DPCT1013: The rounding mode could not be specified and the generated
83        code may have different accuracy than the original code. Verify the
84        correctness. SYCL math built-in function rounding mode is aligned with
85        OpenCL C 1.2 standard.
86        */
87        const float product = x * w;
88        gate[i] = product;
89        /*
90        DPCT1013: The rounding mode could not be specified and the generated
91        code may have different accuracy than the original code. Verify the
92        correctness. SYCL math built-in function rounding mode is aligned with
93        OpenCL C 1.2 standard.
94        */
95        if constexpr (Fused) sum = sycl::fma(x, w, sum);
96        /*
97        DPCT1013: The rounding mode could not be specified and the generated
98        code may have different accuracy than the original code. Verify the
99        correctness. SYCL math built-in function rounding mode is aligned with
100        OpenCL C 1.2 standard.
101        */
102        else sum = c == 0 ? product : sum + product;
103    }
104    if constexpr (Fused) mixed[d] = scale * sum;
105    else mixed[d] = scale_zero_bias(sum, scale);
106}
107__dpct_inline__ void post(const float *residual,
108                          const float *__restrict__ block_out,
109                          const float *__restrict__ inject, float *output,
110                          int n_embd, int hc, float scale) {
111    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
112    const std::size_t i =
113        std::size_t(item_ct1.get_group(2)) * item_ct1.get_local_range(2) +
114        item_ct1.get_local_id(2);
115    if (i >= std::size_t(n_embd) * hc) return;
116    const std::size_t t = item_ct1.get_group(1);
117    residual += t * std::size_t(n_embd) * hc;
118    block_out += t * std::size_t(n_embd);
119    inject += t * std::size_t(hc);
120    output += t * std::size_t(n_embd) * hc;
121    const int c = int(i / n_embd), d = int(i % n_embd);
122    const float weight = scale_zero_bias(sigmoid(scale_zero_bias(inject[c], scale)), 2.0f);
123    // Exact residual/output alias is supported; no other thread reads residual[i].
124    /*
125    DPCT1013: The rounding mode could not be specified and the generated
126    code may have different accuracy than the original code. Verify the
127    correctness. SYCL math built-in function rounding mode is aligned with
128    OpenCL C 1.2 standard.
129    */
130    output[i] = sycl::fma(block_out[d], weight, residual[i]);
131}
132void check_pointer(const void* p) {
133    if (!p || reinterpret_cast<std::uintptr_t>(p) % alignof(float))
134        throw std::invalid_argument("native GR postops require non-null four-byte aligned pointers");
135}
136void check_shape(int n, int hc) {
137    if (n <= 0 || hc <= 0 || std::uint64_t(n) * hc > std::uint64_t(std::numeric_limits<int>::max()))
138        throw std::invalid_argument("native GR postops require positive bounded dimensions");
139}
140unsigned blocks(std::size_t n) { return unsigned((n + THREADS - 1) / THREADS); }
141void check_launch() {
142    /*
143    DPCT1010: SYCL uses exceptions to report errors and does not use the
144    error codes. The cudaGetLastError function call was replaced with 0. You
145    need to rewrite this code.
146    */
147    const auto error = 0;
148    /*
149    DPCT1000: Error handling if-stmt was detected but could not be
150    rewritten.
151    */
152    if (error != 0)
153        /*
154        DPCT1009: SYCL reports errors using exceptions and does not use
155        error codes. Please replace the "get_error_string_dummy(...)" with a
156        real error-handling function.
157        */
158        /*
159        DPCT1001: The statement could not be removed.
160        */
161        throw std::runtime_error(std::string("native GR postops launch: ") +
162                                 dpct::get_error_string_dummy(error));
163}
164} // namespace
165
166void native_gr_down_silu(float* lo, int hc_lr, int hc, void* stream) {
167    check_shape(hc_lr, hc);
168    check_pointer(lo);
169    {
170        auto exp_props = sycl::ext::oneapi::experimental::properties{
171            sycl::ext::oneapi::experimental::use_root_sync};
172
173        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
174            ->submit([&](sycl::handler &cgh) {
175                auto float_hc_ct2 = 1.0f / float(hc);
176
177                cgh.parallel_for<dpct_kernel_name<class down_silu_24f4fb>>(
178                    sycl::nd_range<3>(sycl::range(1, 1, blocks(hc_lr)) *
179                                          sycl::range(1, 1, THREADS),
180                                      sycl::range(1, 1, THREADS)),
181                    exp_props, [=](sycl::nd_item<3> item_ct1) {
182                        down_silu(lo, hc_lr, float_hc_ct2);
183                    });
184            });
185    }
186    check_launch();
187}
188void native_gr_pre_gated(const float* xn, float* gate, float* mixed,
189                         int n_embd, int hc, bool fused_layer, void* stream) {
190    native_gr_pre_gated_multi(xn, gate, mixed, n_embd, hc, 1, fused_layer, stream);
191}
192void native_gr_pre_gated_multi(const float* xn, float* gate, float* mixed,
193                               int n_embd, int hc, int n_tok, bool fused_layer, void* stream) {
194    if (n_tok <= 0)
195        throw std::invalid_argument("native GR postops require positive n_tok");
196    check_shape(n_embd, hc);
197    check_pointer(xn); check_pointer(gate); check_pointer(mixed);
198    const dpct::dim3 grid{blocks(n_embd), unsigned(n_tok), 1u};
199    if (fused_layer)
200    {
201        auto exp_props = sycl::ext::oneapi::experimental::properties{
202            sycl::ext::oneapi::experimental::use_root_sync};
203
204        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
205            ->submit([&](sycl::handler &cgh) {
206                auto float_hc_ct5 = 1.0f / float(hc);
207
208                cgh.parallel_for<dpct_kernel_name<class pre_gated_e6e3d1,
209                                                  dpct_kernel_scalar<true>>>(
210                    sycl::nd_range<3>(grid * sycl::range(1, 1, THREADS),
211                                      sycl::range(1, 1, THREADS)),
212                    exp_props, [=](sycl::nd_item<3> item_ct1) {
213                        pre_gated<true>(xn, gate, mixed, n_embd, hc,
214                                        float_hc_ct5);
215                    });
216            });
217    } else {
218        auto exp_props = sycl::ext::oneapi::experimental::properties{
219            sycl::ext::oneapi::experimental::use_root_sync};
220
221        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
222            ->submit([&](sycl::handler &cgh) {
223                auto float_hc_ct5 = 1.0f / float(hc);
224
225                cgh.parallel_for<dpct_kernel_name<class pre_gated_10bc88,
226                                                  dpct_kernel_scalar<false>>>(
227                    sycl::nd_range<3>(grid * sycl::range(1, 1, THREADS),
228                                      sycl::range(1, 1, THREADS)),
229                    exp_props, [=](sycl::nd_item<3> item_ct1) {
230                        pre_gated<false>(xn, gate, mixed, n_embd, hc,
231                                         float_hc_ct5);
232                    });
233            });
234    }
235    check_launch();
236}
237void native_gr_post(const float* residual, const float* block_out, const float* inject,
238                    float* output, int n_embd, int hc, void* stream) {
239    native_gr_post_multi(residual, block_out, inject, output, n_embd, hc, 1, stream);
240}
241void native_gr_post_multi(const float* residual, const float* block_out, const float* inject,
242                          float* output, int n_embd, int hc, int n_tok, void* stream) {
243    if (n_tok <= 0)
244        throw std::invalid_argument("native GR postops require positive n_tok");
245    check_shape(n_embd, hc);
246    check_pointer(residual); check_pointer(block_out); check_pointer(inject); check_pointer(output);
247    const dpct::dim3 grid{blocks(std::size_t(n_embd) * hc), unsigned(n_tok),
248                          1u};
249    {
250        auto exp_props = sycl::ext::oneapi::experimental::properties{
251            sycl::ext::oneapi::experimental::use_root_sync};
252
253        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
254            ->submit([&](sycl::handler &cgh) {
255                auto float_hc_ct6 = 1.0f / float(hc);
256
257                cgh.parallel_for<dpct_kernel_name<class post_a7f844>>(
258                    sycl::nd_range<3>(grid * sycl::range(1, 1, THREADS),
259                                      sycl::range(1, 1, THREADS)),
260                    exp_props, [=](sycl::nd_item<3> item_ct1) {
261                        post(residual, block_out, inject, output, n_embd, hc,
262                             float_hc_ct6);
263                    });
264            });
265    }
266    check_launch();
267}
268} // namespace strata::kernels