okami.mom/strata

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

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

main
7.1 KiB173 linesraw
1// Adapted from llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d:
2// ggml/src/ggml-cuda/{norm.cu,common.cuh}. Scope: contiguous weighted F32 RMSNorm.
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_norm.hpp"
31
32#include <cmath>
33#include <cstddef>
34#include <cstdint>
35#include <stdexcept>
36#include <string>
37
38namespace strata::kernels {
39namespace {
40
41__dpct_inline__ float norm_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    }
53    return value;
54}
55
56template <int BlockSize>
57__dpct_inline__ void weighted_rms_norm(const float *__restrict__ input,
58                                       const float *__restrict__ gamma,
59                                       float *__restrict__ output, int n_cols,
60                                       float epsilon) {
61    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
62    const int tid = item_ct1.get_local_id(2);
63    const std::size_t row =
64        std::size_t(item_ct1.get_group(1)) * item_ct1.get_group_range(2) +
65        item_ct1.get_group(2);
66    const std::size_t row_offset = row * n_cols;
67    input += row_offset;
68    gamma += std::size_t(item_ct1.get_group(2)) * n_cols;
69    output += row_offset;
70    float partial = 0.0f;
71    for (int col = tid; col < n_cols; col += BlockSize) {
72        const float value = input[col];
73        partial += value * value;
74    }
75
76    // Pinned block_reduce<SUM,BlockSize>: every warp repeats the final XOR
77    // reduction. There is no warp-0-only broadcast or downward-shuffle tree.
78    auto &sums =
79        *sycl::ext::oneapi::group_local_memory_for_overwrite<float[32]>(
80            sycl::ext::oneapi::this_work_item::get_work_group<3>());
81    partial = norm_warp_sum(partial);
82    const int lane = tid % 32;
83    if (lane == 0) sums[tid / 32] = partial;
84    item_ct1.barrier(sycl::access::fence_space::local_space);
85    partial = 0.0f;
86    if (lane < BlockSize / 32) partial = sums[lane];
87    partial = norm_warp_sum(partial);
88
89    const float mean = partial / n_cols;
90    const float scale = sycl::rsqrt(mean + epsilon);
91#pragma unroll
92    for (int col = tid; col < n_cols; col += BlockSize) {
93        output[col] = scale * input[col] * gamma[col];
94    }
95}
96
97void check_pointer(const void* p) {
98    if (!p || reinterpret_cast<std::uintptr_t>(p) % alignof(float) != 0)
99        throw std::invalid_argument("native GR RMSNorm requires non-null four-byte aligned pointers");
100}
101
102} // namespace
103
104void native_gr_rms_norm_weighted(const float* input, const float* gamma, float* output,
105                                 int n_cols, int n_rows, float epsilon, void* stream) {
106    native_gr_rms_norm_weighted_multi(input, gamma, output, n_cols, n_rows, 1, epsilon, stream);
107}
108
109void native_gr_rms_norm_weighted_multi(const float* input, const float* gamma, float* output,
110                                       int n_cols, int n_rows, int n_tok, float epsilon, void* stream) {
111    if (n_cols <= 0 || n_rows <= 0 || n_tok <= 0 || !std::isfinite(epsilon) || epsilon < 0.0f)
112        throw std::invalid_argument("native GR RMSNorm requires positive dimensions and finite nonnegative epsilon");
113    check_pointer(input);
114    check_pointer(gamma);
115    check_pointer(output);
116    const auto cuda_stream = strata::q_of(stream);
117    const dpct::dim3 grid{unsigned(n_rows), unsigned(n_tok), 1u};
118    if (n_cols < 1024)
119    {
120        auto exp_props = sycl::ext::oneapi::experimental::properties{
121            sycl::ext::oneapi::experimental::use_root_sync};
122
123        strata::kprof::kp(cuda_stream, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<
124            class weighted_rms_norm_60b509, dpct_kernel_scalar<256>>>(
125            sycl::nd_range<3>(grid * sycl::range(1, 1, 256),
126                              sycl::range(1, 1, 256)),
127            exp_props,
128            [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {
129                weighted_rms_norm<256>(input, gamma, output, n_cols, epsilon);
130            });
131    } else
132    /*
133    DPCT1049: The work-group size passed to the SYCL kernel may exceed
134    the limit. To get the device limit, query
135    info::device::max_work_group_size. Adjust the work-group size if needed.
136    */
137    {
138        auto exp_props = sycl::ext::oneapi::experimental::properties{
139            sycl::ext::oneapi::experimental::use_root_sync};
140
141        strata::kprof::kp(cuda_stream, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<
142            class weighted_rms_norm_9382c8, dpct_kernel_scalar<1024>>>(
143            sycl::nd_range<3>(grid * sycl::range(1, 1, 1024),
144                              sycl::range(1, 1, 1024)),
145            exp_props,
146            [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {
147                weighted_rms_norm<1024>(input, gamma, output, n_cols, epsilon);
148            });
149    }
150    /*
151    DPCT1010: SYCL uses exceptions to report errors and does not use the
152    error codes. The cudaGetLastError function call was replaced with 0. You
153    need to rewrite this code.
154    */
155    const auto error = 0;
156    /*
157    DPCT1000: Error handling if-stmt was detected but could not be
158    rewritten.
159    */
160    if (error != 0)
161        /*
162        DPCT1009: SYCL reports errors using exceptions and does not use
163        error codes. Please replace the "get_error_string_dummy(...)" with a
164        real error-handling function.
165        */
166        /*
167        DPCT1001: The statement could not be removed.
168        */
169        throw std::runtime_error(std::string("native GR RMSNorm launch: ") +
170                                 dpct::get_error_string_dummy(error));
171}
172
173} // namespace strata::kernels