okami.mom/strata

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

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

main
13.3 KiB289 linesraw
1// Adapted from llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d:
2// ggml/src/ggml-cuda/{norm.cu,common.cuh,unary.cu}.
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_qsa.hpp"
31#include <atomic>
32#include <cmath>
33#include <cstddef>
34#include <cstdint>
35#include <limits>
36#include <stdexcept>
37#include <string>
38
39namespace strata::kernels {
40namespace {
41std::atomic<bool> enabled{false};
42__dpct_inline__ float warp_sum(float value) {
43#pragma unroll
44    for (int offset = 16; offset; offset >>= 1)
45        /*
46        DPCT1108: '__shfl_xor_sync' was migrated with the experimental
47        feature masked sub_group function which may not be supported by all
48        compilers or runtimes. You may need to adjust the code.
49        */
50        value += dpct::experimental::permute_sub_group_by_xor(
51            0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),
52            value, offset);
53    return value;
54}
55template <int BlockSize>
56__dpct_inline__ void norm(const float *input, const float *__restrict__ gamma,
57                          float *output, int n_cols, float epsilon) {
58    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
59    const int tid = item_ct1.get_local_id(2);
60    const std::size_t row_offset = std::size_t(item_ct1.get_group(2)) * n_cols;
61    input += row_offset; output += row_offset;
62    float partial = 0.0f;
63    for (std::size_t col = tid; col < std::size_t(n_cols); col += BlockSize) {
64        const float x = input[col];
65        partial += x * x;
66    }
67    auto &sums =
68        *sycl::ext::oneapi::group_local_memory_for_overwrite<float[32]>(
69            sycl::ext::oneapi::this_work_item::get_work_group<3>());
70    partial = warp_sum(partial);
71    const int lane = tid % 32;
72    if (lane == 0) sums[tid / 32] = partial;
73    // All reads of input for the reduction precede this barrier. Afterwards,
74    // each thread reads/writes only its own elements, allowing exact in-place use.
75    item_ct1.barrier(sycl::access::fence_space::local_space);
76    partial = lane < BlockSize / 32 ? sums[lane] : 0.0f;
77    partial = warp_sum(partial);
78    const float mean = partial / n_cols;
79    const float scale = sycl::rsqrt(mean + epsilon);
80#pragma unroll
81    for (std::size_t col = tid; col < std::size_t(n_cols); col += BlockSize)
82        output[col] = scale * input[col] * gamma[col];
83}
84// As norm, with gamma[groups * n_cols]: row r is group r % groups and reads its own slice of gamma.
85template <int BlockSize>
86__dpct_inline__ void
87norm_grouped(const float *input, const float *__restrict__ gamma, float *output,
88             int n_cols, int groups, float epsilon) {
89    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
90    const int tid = item_ct1.get_local_id(2);
91    const std::size_t row_offset = std::size_t(item_ct1.get_group(2)) * n_cols;
92    input += row_offset; output += row_offset;
93    gamma += std::size_t(item_ct1.get_group(2) % unsigned(groups)) * n_cols;
94    float partial = 0.0f;
95    for (std::size_t col = tid; col < std::size_t(n_cols); col += BlockSize) {
96        const float x = input[col];
97        partial += x * x;
98    }
99    auto &sums =
100        *sycl::ext::oneapi::group_local_memory_for_overwrite<float[32]>(
101            sycl::ext::oneapi::this_work_item::get_work_group<3>());
102    partial = warp_sum(partial);
103    const int lane = tid % 32;
104    if (lane == 0) sums[tid / 32] = partial;
105    item_ct1.barrier(sycl::access::fence_space::local_space);
106    partial = lane < BlockSize / 32 ? sums[lane] : 0.0f;
107    partial = warp_sum(partial);
108    const float mean = partial / n_cols;
109    const float scale = sycl::rsqrt(mean + epsilon);
110#pragma unroll
111    for (std::size_t col = tid; col < std::size_t(n_cols); col += BlockSize)
112        output[col] = scale * input[col] * gamma[col];
113}
114__dpct_inline__ void gate(const float *attn, const float *__restrict__ q_full,
115                          float *output, int n_head, int head_dim) {
116    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
117    const std::size_t i =
118        std::size_t(item_ct1.get_group(2)) * item_ct1.get_local_range(2) +
119        item_ct1.get_local_id(2);
120    if (i >= std::size_t(n_head) * head_dim) return;
121    const std::size_t head = i / head_dim, channel = i % head_dim;
122    const float raw = q_full[head * 2 * head_dim + head_dim + channel];
123    const float sigmoid = 1.0f / (1.0f + sycl::native::exp(-raw));
124    output[i] = attn[i] * sigmoid;
125}
126std::size_t elements(int cols, int rows) {
127    if (cols <= 0 || rows <= 0 || std::uint64_t(cols) * rows > std::uint64_t(std::numeric_limits<int>::max()))
128        throw std::invalid_argument("native QSA requires positive bounded dimensions");
129    return std::size_t(cols) * rows;
130}
131bool valid(const void* ptr, std::size_t bytes) {
132    const auto address = reinterpret_cast<std::uintptr_t>(ptr);
133    return ptr && address % 4 == 0 && bytes <= UINTPTR_MAX - address;
134}
135bool overlap(const void* a, std::size_t an, const void* b, std::size_t bn) {
136    const auto ap = reinterpret_cast<std::uintptr_t>(a), bp = reinterpret_cast<std::uintptr_t>(b);
137    return ap < bp + bn && bp < ap + an;
138}
139void buffers(const float* input, std::size_t in_bytes, const float* weight, std::size_t weight_bytes,
140             float* output, void* stream) {
141    if (!stream || !valid(input, in_bytes) || !valid(weight, weight_bytes) || !valid(output, in_bytes) ||
142        overlap(input, in_bytes, weight, weight_bytes) || overlap(output, in_bytes, weight, weight_bytes) ||
143        (input != output && overlap(input, in_bytes, output, in_bytes)))
144        throw std::invalid_argument("native QSA requires a stream, aligned spans, and disjoint buffers or exact input/output alias");
145}
146void check_launch() {
147    /*
148    DPCT1010: SYCL uses exceptions to report errors and does not use the
149    error codes. The cudaGetLastError function call was replaced with 0. You
150    need to rewrite this code.
151    */
152    const auto result = 0;
153    /*
154    DPCT1000: Error handling if-stmt was detected but could not be
155    rewritten.
156    */
157    if (result != 0)
158        /*
159        DPCT1009: SYCL reports errors using exceptions and does not use
160        error codes. Please replace the "get_error_string_dummy(...)" with a
161        real error-handling function.
162        */
163        /*
164        DPCT1001: The statement could not be removed.
165        */
166        throw std::runtime_error(std::string("native QSA launch: ") +
167                                 dpct::get_error_string_dummy(result));
168}
169} // namespace
170
171void native_qsa_set_enabled(bool value) { enabled.store(value, std::memory_order_relaxed); }
172bool native_qsa_enabled() { return enabled.load(std::memory_order_relaxed); }
173
174void native_qsa_rms_norm_weighted(const float* input, const float* gamma, float* output,
175                                  int n_cols, int n_rows, float epsilon, void* stream) {
176    const auto count = elements(n_cols, n_rows);
177    if (!std::isfinite(epsilon) || epsilon < 0.0f)
178        throw std::invalid_argument("native QSA requires finite nonnegative epsilon");
179    buffers(input, count * 4, gamma, std::size_t(n_cols) * 4, output, stream);
180    if (n_cols < 1024)
181    {
182        auto exp_props = sycl::ext::oneapi::experimental::properties{
183            sycl::ext::oneapi::experimental::use_root_sync};
184
185        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
186            ->template parallel_for<
187                dpct_kernel_name<class norm_5d08bf, dpct_kernel_scalar<256>>>(
188                sycl::nd_range<3>(sycl::range(1, 1, unsigned(n_rows)) *
189                                      sycl::range(1, 1, 256),
190                                  sycl::range(1, 1, 256)),
191                exp_props,
192                [=](sycl::nd_item<3> item_ct1)
193                    [[sycl::reqd_sub_group_size(32)]] {
194                        norm<256>(input, gamma, output, n_cols, epsilon);
195                    });
196    } else
197    /*
198    DPCT1049: The work-group size passed to the SYCL kernel may exceed
199    the limit. To get the device limit, query
200    info::device::max_work_group_size. Adjust the work-group size if needed.
201    */
202    {
203        auto exp_props = sycl::ext::oneapi::experimental::properties{
204            sycl::ext::oneapi::experimental::use_root_sync};
205
206        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
207            ->template parallel_for<
208                dpct_kernel_name<class norm_127936, dpct_kernel_scalar<1024>>>(
209                sycl::nd_range<3>(sycl::range(1, 1, unsigned(n_rows)) *
210                                      sycl::range(1, 1, 1024),
211                                  sycl::range(1, 1, 1024)),
212                exp_props,
213                [=](sycl::nd_item<3> item_ct1)
214                    [[sycl::reqd_sub_group_size(32)]] {
215                        norm<1024>(input, gamma, output, n_cols, epsilon);
216                    });
217    }
218    check_launch();
219}
220void native_qsa_rms_norm_grouped(const float* input, const float* gamma, float* output,
221                                 int n_cols, int groups, int n_rows, float epsilon, void* stream) {
222    if (groups < 1) throw std::invalid_argument("native QSA requires positive bounded dimensions");
223    const auto count = elements(n_cols, n_rows);
224    if (!std::isfinite(epsilon) || epsilon < 0.0f)
225        throw std::invalid_argument("native QSA requires finite nonnegative epsilon");
226    buffers(input, count * 4, gamma, std::size_t(n_cols) * groups * 4, output, stream);
227    if (n_cols < 1024)
228    {
229        auto exp_props = sycl::ext::oneapi::experimental::properties{
230            sycl::ext::oneapi::experimental::use_root_sync};
231
232        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
233            ->template parallel_for<dpct_kernel_name<class norm_grouped_b5907a,
234                                            dpct_kernel_scalar<256>>>(
235                sycl::nd_range<3>(sycl::range(1, 1, unsigned(n_rows)) *
236                                      sycl::range(1, 1, 256),
237                                  sycl::range(1, 1, 256)),
238                exp_props,
239                [=](sycl::nd_item<3> item_ct1)
240                    [[sycl::reqd_sub_group_size(32)]] {
241                        norm_grouped<256>(input, gamma, output, n_cols, groups,
242                                          epsilon);
243                    });
244    } else
245    /*
246    DPCT1049: The work-group size passed to the SYCL kernel may exceed
247    the limit. To get the device limit, query
248    info::device::max_work_group_size. Adjust the work-group size if needed.
249    */
250    {
251        auto exp_props = sycl::ext::oneapi::experimental::properties{
252            sycl::ext::oneapi::experimental::use_root_sync};
253
254        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
255            ->template parallel_for<dpct_kernel_name<class norm_grouped_927e80,
256                                            dpct_kernel_scalar<1024>>>(
257                sycl::nd_range<3>(sycl::range(1, 1, unsigned(n_rows)) *
258                                      sycl::range(1, 1, 1024),
259                                  sycl::range(1, 1, 1024)),
260                exp_props,
261                [=](sycl::nd_item<3> item_ct1)
262                    [[sycl::reqd_sub_group_size(32)]] {
263                        norm_grouped<1024>(input, gamma, output, n_cols, groups,
264                                           epsilon);
265                    });
266    }
267    check_launch();
268}
269void native_qsa_gate_apply(const float* attn, const float* q_full, float* output,
270                           int n_head, int head_dim, void* stream) {
271    const auto count = elements(head_dim, n_head);
272    buffers(attn, count * 4, q_full, count * 8, output, stream);
273    {
274        auto exp_props = sycl::ext::oneapi::experimental::properties{
275            sycl::ext::oneapi::experimental::use_root_sync};
276
277        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
278            ->template parallel_for<dpct_kernel_name<class gate_148967>>(
279                sycl::nd_range<3>(
280                    sycl::range(1, 1, unsigned((count + 255) / 256)) *
281                        sycl::range(1, 1, 256),
282                    sycl::range(1, 1, 256)),
283                exp_props, [=](sycl::nd_item<3> item_ct1) {
284                    gate(attn, q_full, output, n_head, head_dim);
285                });
286    }
287    check_launch();
288}
289} // namespace strata::kernels