okami.mom/strata

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

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

main
19.2 KiB422 linesraw
1// Numerical contract: pinned ggml/src/ggml-cuda/rope.cu, rope_multi/rope_yarn.
2// Text positions are equal across the four IMRoPE sections, so section routing
3// reduces to the one position associated with each contiguous row.
4// MIT License
5//
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_rope.hpp"
31#include "strata/kernels/mrope.hpp"
32#include <atomic>
33#include <cmath>
34#include <cstdint>
35#include <cstdlib>
36#include <limits>
37#include <stdexcept>
38
39namespace strata::kernels {
40namespace {
41std::atomic<bool> enabled{false};
42bool overlaps(const void* a, size_t an, const void* b, size_t bn) {
43    auto x = reinterpret_cast<uintptr_t>(a), y = reinterpret_cast<uintptr_t>(b);
44    return x <= y ? y - x < an : x - y < bn;
45}
46// TAB (#280, STRATA_ROPE_TABLE=1): the angles from the session's float64 table.  The host launches <false> whenever
47// no table applies - the default - so the default kernel is 0.1.31's code exactly (the table read is not in it;
48// with it merely skipped at run time, the compiled default path changed its results).
49template <bool TAB>
50__dpct_inline__ void apply(const float *x, float *out, int rows, int width,
51                           int n_rot, float theta_scale, float freq_scale,
52                           float corr_low, float corr_high, float ext_factor,
53                           float mscale, const int *positions,
54                           const int32_t *mtab, RopeTab rt) {
55    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
56    const int row = item_ct1.get_group(1);
57    const int pair = item_ct1.get_group(2) * item_ct1.get_local_range(2) +
58                     item_ct1.get_local_id(2);
59    if (row >= rows || pair >= width / 2) return;
60    const size_t start = size_t(row) * width;
61    if (pair >= n_rot / 2) {
62        if (x != out) {
63            out[start + 2 * pair] = x[start + 2 * pair];
64            out[start + 2 * pair + 1] = x[start + 2 * pair + 1];
65        }
66        return;
67    }
68    float c, s;
69    if (!(TAB && rope_tab_cs(rt, mrope_pos(mtab, positions[row], pair), pair, c, s))) {
70        const float theta_extrap = mrope_pos(mtab, positions[row], pair) *
71                                   dpct::pow(theta_scale, float(pair));
72        rope_scaled_angle(theta_extrap, freq_scale, corr_low, corr_high, ext_factor, mscale, pair, c, s);
73    }
74    const float a = x[start + pair], b = x[start + pair + n_rot / 2];
75    out[start + pair] = a * c - b * s;
76    out[start + pair + n_rot / 2] = a * s + b * c;
77}
78
79template <bool TAB>
80__dpct_inline__ void
81norm_rope_kernel(const float *x, int in_stride, const float *__restrict__ gamma,
82                 float *out, int n_cols, int n_rot, float epsilon,
83                 float theta_scale, float freq_scale, float corr_low,
84                 float corr_high, float ext_factor, float mscale,
85                 const int *positions, const int32_t *mtab, RopeTab rt) {
86    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
87    const int tid = item_ct1.get_local_id(2);
88    const int row = item_ct1.get_group(2);
89    const float* in_row = x + size_t(row) * in_stride;
90    float* out_row = out + size_t(row) * n_cols;
91    float partial = 0.0f;
92    for (size_t col = tid; col < size_t(n_cols); col += 256) {
93        const float xv = in_row[col];
94        partial += xv * xv;
95    }
96    const int half_rot = n_rot / 2;
97    const float x_tid = tid < n_cols ? in_row[tid] : 0.0f;
98    const float x_hi  = tid < half_rot ? in_row[tid + half_rot] : 0.0f;
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#pragma unroll
103    for (int offset = 16; offset; offset >>= 1)
104        /*
105        DPCT1108: '__shfl_xor_sync' was migrated with the experimental
106        feature masked sub_group function which may not be supported by all
107        compilers or runtimes. You may need to adjust the code.
108        */
109        partial += dpct::experimental::permute_sub_group_by_xor(
110            0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),
111            partial, offset);
112    const int lane = tid % 32;
113    if (lane == 0) sums[tid / 32] = partial;
114    /*
115    DPCT1065: Consider replacing sycl::nd_item::barrier() with
116    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
117    performance if there is no access to global memory.
118    */
119    item_ct1.barrier();
120    partial = lane < 256 / 32 ? sums[lane] : 0.0f;
121#pragma unroll
122    for (int offset = 16; offset; offset >>= 1)
123        /*
124        DPCT1108: '__shfl_xor_sync' was migrated with the experimental
125        feature masked sub_group function which may not be supported by all
126        compilers or runtimes. You may need to adjust the code.
127        */
128        partial += dpct::experimental::permute_sub_group_by_xor(
129            0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),
130            partial, offset);
131    const float mean = partial / n_cols;
132    const float scale = sycl::rsqrt(mean + epsilon);
133    if (tid >= n_rot && tid < n_cols) {
134        out_row[tid] = (scale * x_tid) * gamma[tid];
135    } else if (tid < half_rot) {
136        const int pair = tid;
137        float a = (scale * x_tid) * gamma[pair];
138        float b = (scale * x_hi) * gamma[pair + half_rot];
139#if defined(DPCT_COMPATIBILITY_TEMP) && !defined(__HIP_DEVICE_COMPILE__)
140#if defined(__SYCL_DEVICE_ONLY__) && defined(__NVPTX__)
141        asm volatile("mov.f32 %0, %1;" : "=f"(a) : "f"(a));
142#else
143        a = a;
144#endif
145#if defined(__SYCL_DEVICE_ONLY__) && defined(__NVPTX__)
146        asm volatile("mov.f32 %0, %1;" : "=f"(b) : "f"(b));
147#else
148        b = b;
149#endif
150#endif
151        float c, s;
152        if (!(TAB && rope_tab_cs(rt, mrope_pos(mtab, positions[row], pair), pair, c, s))) {
153            const float theta_extrap = mrope_pos(mtab, positions[row], pair) *
154                                       dpct::pow(theta_scale, float(pair));
155            rope_scaled_angle(theta_extrap, freq_scale, corr_low, corr_high, ext_factor, mscale, pair, c, s);
156        }
157        float bs = b * s;
158        float bc = b * c;
159#if defined(DPCT_COMPATIBILITY_TEMP) && !defined(__HIP_DEVICE_COMPILE__)
160#if defined(__SYCL_DEVICE_ONLY__) && defined(__NVPTX__)
161        asm volatile("mov.f32 %0, %1;" : "=f"(bs) : "f"(bs));
162#else
163        bs = bs;
164#endif
165#if defined(__SYCL_DEVICE_ONLY__) && defined(__NVPTX__)
166        asm volatile("mov.f32 %0, %1;" : "=f"(bc) : "f"(bc));
167#else
168        bc = bc;
169#endif
170#endif
171        out_row[pair] = sycl::fma(a, c, -bs);
172        out_row[pair + half_rot] = sycl::fma(a, s, bc);
173    }
174}
175}
176// one table per device (a layer split runs the rope kernels on several): set and read for the current device
177namespace {
178constexpr int kMropeDevices = 64;
179std::atomic<const int32_t*> mrope_tab[kMropeDevices] = {};
180int mrope_dev() try {
181    int d = 0;
182    if (DPCT_CHECK_ERROR(d = dpct::get_current_device_id()) != 0 || d < 0 ||
183        d >= kMropeDevices) d = 0;
184    return d;
185}
186catch (sycl::exception const &exc) {
187  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
188            << ", line:" << __LINE__ << std::endl;
189  std::exit(1);
190}
191}  // namespace
192void mrope_table_set(const int32_t* device_table) { mrope_tab[mrope_dev()].store(device_table, std::memory_order_relaxed); }
193const int32_t* mrope_table() { return mrope_tab[mrope_dev()].load(std::memory_order_relaxed); }
194namespace {
195// #280: the float64 angle table of each device, set at session init (before any graph is captured)
196struct RopeReg {
197    RopeTab tab;
198    RopeScaling scaling;
199};
200RopeReg rope_tab[kMropeDevices] = {};
201bool same_scaling(const RopeScaling& a, const RopeScaling& b) {
202    return a.type == b.type && a.freq_base == b.freq_base && a.factor == b.factor && a.freq_scale_in == b.freq_scale_in &&
203           a.orig_ctx == b.orig_ctx && a.ext_factor == b.ext_factor && a.attn_factor == b.attn_factor &&
204           a.beta_fast == b.beta_fast && a.beta_slow == b.beta_slow;
205}
206// opt-in: STRATA_ROPE_TABLE=1 (the table's angles differ from the fast-math ones in the last bits, so outputs move)
207bool rope_table_enabled() {
208    static const bool on = [] {
209        const char* e = std::getenv("STRATA_ROPE_TABLE");
210        return e != nullptr && e[0] == '1';
211    }();
212    return on;
213}
214}  // namespace
215void rope_table_set(const float* cos_tab, const float* sin_tab, int max_pos, const RopeScaling& scaling) {
216    rope_tab[mrope_dev()] = RopeReg{RopeTab{cos_tab, sin_tab, max_pos}, scaling};
217}
218void rope_table_release(const float* cos_tab) {
219    // every device's entry that points at it (the caller may free it from another current device)
220    for (RopeReg& r : rope_tab)
221        if (cos_tab != nullptr && r.tab.cos == cos_tab) r = RopeReg{};
222}
223RopeTab rope_table_for(const RopeScaling& scaling) {
224    if (!rope_table_enabled()) return {};
225    const RopeReg& r = rope_tab[mrope_dev()];
226    return r.tab.cos != nullptr && same_scaling(r.scaling, scaling) ? r.tab : RopeTab{};
227}
228void native_rope_set_enabled(bool value) { enabled.store(value, std::memory_order_relaxed); }
229bool native_rope_enabled() { return enabled.load(std::memory_order_relaxed); }
230bool native_norm_rope_usable(int head_dim, int n_rot) {
231    static const bool on = [] {
232        const char* off = std::getenv("STRATA_NO_NORM_ROPE");
233        if (off != nullptr && off[0] != '\0' && off[0] != '0') return false;
234#if defined(__HIPCC__)
235        const char* v = std::getenv("STRATA_NORM_ROPE");   // AMD: opt in until rope_parity check 6 passes there
236        return v != nullptr && v[0] != '\0' && v[0] != '0';
237#else
238        return true;
239#endif
240    }();
241    return on && (head_dim == 128 || head_dim == 256) && n_rot == 64;
242}
243
244void native_rope_apply(const float* x, float* out, int rows, int head_dim,
245                       int n_rot, const RopeScaling& scaling, const int* positions, void* stream) {
246    if (!x || !out || !positions || !stream || rows < 1 || rows > 65535 ||
247        (head_dim != 128 && head_dim != 256) || n_rot != 64 ||
248        rope_scaling_invalid(scaling) != nullptr ||
249        reinterpret_cast<uintptr_t>(x) % 4 || reinterpret_cast<uintptr_t>(out) % 4 ||
250        reinterpret_cast<uintptr_t>(positions) % 4) {
251        throw std::invalid_argument("native RoPE requires aligned F32 rows, width 128/256, rotation 64, valid base/scaling and explicit stream");
252    }
253    const size_t bytes = size_t(rows) * head_dim * sizeof(float);
254    if ((x != out && overlaps(x, bytes, out, bytes)) ||
255        overlaps(positions, size_t(rows) * sizeof(int), out, bytes) ||
256        overlaps(positions, size_t(rows) * sizeof(int), x, bytes)) {
257        throw std::invalid_argument("native RoPE buffers partially overlap");
258    }
259    // Match pinned host-side float powf before device fast powf/trigonometry.
260    const float theta_scale = powf((float) scaling.freq_base, -2.0f / n_rot);
261    const RopeKernelArgs k = scaling.kernel_args(n_rot);   // none: the identity constants
262    const RopeTab rt = rope_table_for(scaling);
263    const unsigned threads = (x == out && n_rot == 64 && native_norm_rope_usable(head_dim, n_rot)) ? 32u : 128u;
264    const dpct::dim3 grid(
265        threads == 32u ? 1u : unsigned((head_dim / 2 + 127) / 128), rows);
266    if (rt.cos != nullptr)
267        /*
268        DPCT1049: The work-group size passed to the SYCL kernel may exceed
269        the limit. To get the device limit, query
270        info::device::max_work_group_size. Adjust the work-group size if needed.
271        */
272    {
273        auto exp_props = sycl::ext::oneapi::experimental::properties{
274            sycl::ext::oneapi::experimental::use_root_sync};
275
276        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
277            ->submit([&](sycl::handler &cgh) {
278                auto mrope_table_ct12 = mrope_table();
279
280                cgh.parallel_for<dpct_kernel_name<class apply_b955ef,
281                                                  dpct_kernel_scalar<true>>>(
282                    sycl::nd_range<3>(grid * sycl::range(1, 1, threads),
283                                      sycl::range(1, 1, threads)),
284                    exp_props, [=](sycl::nd_item<3> item_ct1) {
285                        apply<true>(x, out, rows, head_dim, n_rot, theta_scale,
286                                    k.freq_scale, k.corr_low, k.corr_high,
287                                    k.ext_factor, k.attn_factor, positions,
288                                    mrope_table_ct12, rt);
289                    });
290            });
291    } else
292    /*
293    DPCT1049: The work-group size passed to the SYCL kernel may exceed
294    the limit. To get the device limit, query
295    info::device::max_work_group_size. Adjust the work-group size if needed.
296    */
297    {
298        auto exp_props = sycl::ext::oneapi::experimental::properties{
299            sycl::ext::oneapi::experimental::use_root_sync};
300
301        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
302            ->submit([&](sycl::handler &cgh) {
303                auto mrope_table_ct12 = mrope_table();
304
305                cgh.parallel_for<dpct_kernel_name<class apply_b955ef,
306                                                  dpct_kernel_scalar<false>>>(
307                    sycl::nd_range<3>(grid * sycl::range(1, 1, threads),
308                                      sycl::range(1, 1, threads)),
309                    exp_props, [=](sycl::nd_item<3> item_ct1) {
310                        apply<false>(x, out, rows, head_dim, n_rot, theta_scale,
311                                     k.freq_scale, k.corr_low, k.corr_high,
312                                     k.ext_factor, k.attn_factor, positions,
313                                     mrope_table_ct12, rt);
314                    });
315            });
316    }
317    /*
318    DPCT1010: SYCL uses exceptions to report errors and does not use the
319    error codes. The cudaGetLastError function call was replaced with 0. You
320    need to rewrite this code.
321    */
322    const auto error = 0;
323    /*
324    DPCT1009: SYCL reports errors using exceptions and does not use error
325    codes. Please replace the "get_error_string_dummy(...)" with a real
326    error-handling function.
327    */
328    /*
329    DPCT1001: The statement could not be removed.
330    */
331    /*
332    DPCT1000: Error handling if-stmt was detected but could not be
333    rewritten.
334    */
335    if (error !=
336        0) throw std::runtime_error(dpct::get_error_string_dummy(error));
337}
338
339void native_qsa_rms_norm_rope(const float* x, int in_stride, const float* gamma, float* out,
340                              int rows, int head_dim, int n_rot, float epsilon,
341                              const RopeScaling& scaling, const int* positions, void* stream) {
342    if (!x || !gamma || !out || !positions || !stream || rows < 1 || rows > 65535 ||
343        (head_dim != 128 && head_dim != 256) || in_stride < head_dim || n_rot != 64 ||
344        !std::isfinite(epsilon) || epsilon < 0.0f ||
345        rope_scaling_invalid(scaling) != nullptr ||
346        reinterpret_cast<uintptr_t>(x) % 4 || reinterpret_cast<uintptr_t>(gamma) % 4 ||
347        reinterpret_cast<uintptr_t>(out) % 4 || reinterpret_cast<uintptr_t>(positions) % 4) {
348        throw std::invalid_argument("native_qsa_rms_norm_rope: invalid arguments");
349    }
350    const float theta_scale = powf((float) scaling.freq_base, -2.0f / n_rot);
351    const RopeKernelArgs k = scaling.kernel_args(n_rot);
352    const RopeTab rt = rope_table_for(scaling);
353    if (rt.cos != nullptr)
354    {
355        auto exp_props = sycl::ext::oneapi::experimental::properties{
356            sycl::ext::oneapi::experimental::use_root_sync};
357
358        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
359            ->submit([&](sycl::handler &cgh) {
360                auto mrope_table_ct14 = mrope_table();
361
362                cgh.parallel_for<dpct_kernel_name<class norm_rope_kernel_c8b2b8,
363                                                  dpct_kernel_scalar<true>>>(
364                    sycl::nd_range<3>(sycl::range(1, 1, unsigned(rows)) *
365                                          sycl::range(1, 1, 256),
366                                      sycl::range(1, 1, 256)),
367                    exp_props,
368                    [=](sycl::nd_item<3> item_ct1)
369                        [[sycl::reqd_sub_group_size(32)]] {
370                            norm_rope_kernel<true>(
371                                x, in_stride, gamma, out, head_dim, n_rot,
372                                epsilon, theta_scale, k.freq_scale, k.corr_low,
373                                k.corr_high, k.ext_factor, k.attn_factor,
374                                positions, mrope_table_ct14, rt);
375                        });
376            });
377    } else {
378        auto exp_props = sycl::ext::oneapi::experimental::properties{
379            sycl::ext::oneapi::experimental::use_root_sync};
380
381        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
382            ->submit([&](sycl::handler &cgh) {
383                auto mrope_table_ct14 = mrope_table();
384
385                cgh.parallel_for<dpct_kernel_name<class norm_rope_kernel_f9c8ef,
386                                                  dpct_kernel_scalar<false>>>(
387                    sycl::nd_range<3>(sycl::range(1, 1, unsigned(rows)) *
388                                          sycl::range(1, 1, 256),
389                                      sycl::range(1, 1, 256)),
390                    exp_props,
391                    [=](sycl::nd_item<3> item_ct1)
392                        [[sycl::reqd_sub_group_size(32)]] {
393                            norm_rope_kernel<false>(
394                                x, in_stride, gamma, out, head_dim, n_rot,
395                                epsilon, theta_scale, k.freq_scale, k.corr_low,
396                                k.corr_high, k.ext_factor, k.attn_factor,
397                                positions, mrope_table_ct14, rt);
398                        });
399            });
400    }
401    /*
402    DPCT1010: SYCL uses exceptions to report errors and does not use the
403    error codes. The cudaGetLastError function call was replaced with 0. You
404    need to rewrite this code.
405    */
406    const auto error = 0;
407    /*
408    DPCT1009: SYCL reports errors using exceptions and does not use error
409    codes. Please replace the "get_error_string_dummy(...)" with a real
410    error-handling function.
411    */
412    /*
413    DPCT1001: The statement could not be removed.
414    */
415    /*
416    DPCT1000: Error handling if-stmt was detected but could not be
417    rewritten.
418    */
419    if (error !=
420        0) throw std::runtime_error(dpct::get_error_string_dummy(error));
421}
422}