okami.mom/strata

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

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

main
8.0 KiB166 linesraw
1// src/kernels/cuda/rope.cu - P2.S2: NEOX partial RoPE.
2//
3// Semantics from `ref/qsa.py` (`rope_freqs` + `rope_neox`), which `bench/micro/rope_xcheck` validates against
4// the oracle:
5//
6//     inv[i] = theta ** (-2i / n_rot)          i in [0, n_rot/2)
7//     ang    = pos * inv
8//     cos, sin = cos(ang), sin(ang)
9//     out[:half]     = a*cos - b*sin            a = x[:half], b = x[half:n_rot]
10//     out[half:n_rot] = a*sin + b*cos
11//
12// THE PAIRING IS NEOX - (i, i + n_rot/2), NOT the adjacent pair (2i, 2i+1).  `ggml.h` writes NEOX
13// n_dims=8 as [ccccssss]; the adjacent-pair ("NORMAL") ordering is the other common convention and choosing
14// wrongly rotates the wrong dimensions together, which produces correctly-shaped output with scrambled
15// content.  It is also PARTIAL: only the first n_rot of head_dim are touched, here 64 of 256.
16//
17// WHY THE TABLE IS BUILT ON THE HOST.  The reference computes the frequencies in FLOAT64 (`theta ** (...)`
18// on a float64 arange, cos/sin in float64).  Reproducing that on device means double-precision pow and cos,
19// which are slow on a consumer GPU and - more to the point - not guaranteed to agree with the host's libm.
20// Building the table once on the host and passing it in makes the TABLE exactly the reference's values and
21// leaves the kernel a pure rotation, so each half can be checked tightly instead of both halves sharing one
22// loose tolerance.  The engine wants a cached table anyway: it is per (n_rot, theta, position), not per token.
23//
24// THE SCALED TABLE IS THE SAME IDEA WITH MORE MATH IN THE HOST LOOP.  Linear rescales the angle by
25// `freq_scale`; YaRN blends extrapolation and interpolation along the pairs (ggml's `rope_yarn`) and folds
26// the mscale magnitude correction into the same cos/sin values.  All of it float64, in the reference's
27// order, so `rope_parity` can hold every variant to a bit-exact float64 transcription of the same spec.
28#define DPCT_PROFILING_ENABLED
29#include <sycl/sycl.hpp>
30#include "strata/kprof.hpp"
31#include <dpct/dpct.hpp>
32#include "strata/sycl_queue.hpp"
33#include "strata/kernels/rope.hpp"
34#include "strata/kernels/mrope.hpp"
35
36#include <cmath>
37#include <cstdio>
38#include <cstdlib>
39
40namespace strata::kernels {
41
42namespace {
43// The process's rope config (rope_scaling.hpp).  One writer - the engine's startup thread, before
44// session_init builds any table or captures any graph - and readers after it.
45RopeScaling g_rope_scaling;
46}  // namespace
47
48void rope_scaling_set(const RopeScaling& scaling) { g_rope_scaling = scaling; }
49const RopeScaling& rope_scaling() { return g_rope_scaling; }
50
51void build_rope_table(int n_rot, double theta, int max_pos, float* cos_tab, float* sin_tab) {
52    const int half = n_rot / 2;
53    for (int p = 0; p < max_pos; ++p) {
54        for (int i = 0; i < half; ++i) {
55            // float64 throughout, in the reference's order: inv, then ang, then cos/sin
56            const double inv = std::pow(theta, -2.0 * (double) i / (double) n_rot);
57            const double ang = (double) p * inv;
58            cos_tab[(size_t) p * half + i] = (float) std::cos(ang);
59            sin_tab[(size_t) p * half + i] = (float) std::sin(ang);
60        }
61    }
62}
63
64void build_rope_table(int n_rot, const RopeScaling& sc, int max_pos, float* cos_tab, float* sin_tab) {
65    if (sc.type == RopeScalingType::None) {
66        build_rope_table(n_rot, sc.freq_base, max_pos, cos_tab, sin_tab);   // the original loop, verbatim
67        return;
68    }
69    const int half = n_rot / 2;
70    const double fs = sc.freq_scale();
71    const double ms = sc.mscale();
72    double cd[2];
73    sc.corr_dims(n_rot, cd);
74    const bool correct = sc.ext_factor != 0;   // ggml: the correction rides on ext_factor, not the type
75    for (int p = 0; p < max_pos; ++p) {
76        for (int i = 0; i < half; ++i) {
77            const double inv = std::pow(sc.freq_base, -2.0 * (double) i / (double) n_rot);
78            const double extrap = (double) p * inv;    // the trained angle, ggml's theta_extrap
79            const double interp = fs * extrap;         // ggml's theta_interp
80            double ang = interp;
81            if (correct) {
82                const double ramp = (double) rope_yarn_ramp((float) cd[0], (float) cd[1], i) * sc.ext_factor;
83                ang = interp * (1.0 - ramp) + extrap * ramp;
84            }
85            cos_tab[(size_t) p * half + i] = (float) (std::cos(ang) * ms);
86            sin_tab[(size_t) p * half + i] = (float) (std::sin(ang) * ms);
87        }
88    }
89}
90
91namespace {
92
93// ONE THREAD PER ROW, not per (row, pair).  The first version had one thread per pair and did the tail copy
94// with 	hreadIdx.x strided loops - so up to 32 threads wrote into the SAME row, with no barrier between the
95// copy and the rotation, and a thread's copy of orow[i] could land AFTER another thread had rotated it.  A
96// race that silently writes the unrotated value is worse than a wrong answer: it is intermittent.
97//
98// A row is head_dim floats (256 here) and there are batch x heads of them, so one thread per row is a
99// handful of threads for a token and removes the ordering question entirely rather than synchronising it.
100__dpct_inline__ void rope_neox_kernel(const float *__restrict__ x,
101                                      float *__restrict__ out, long long rows,
102                                      int head_dim, int n_rot,
103                                      const float *__restrict__ cos_tab,
104                                      const float *__restrict__ sin_tab,
105                                      const int *__restrict__ pos,
106                                      const int32_t *__restrict__ mtab) {
107    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
108    const long long r =
109        (long long)item_ct1.get_group(2) * item_ct1.get_local_range(2) +
110        item_ct1.get_local_id(2);
111    if (r >= rows) return;
112    const int half = n_rot / 2;
113    const float* xr = x + r * head_dim;
114    float* orow = out + r * head_dim;
115
116#pragma unroll
117    for (int d = n_rot; d < head_dim; ++d)
118        orow[d] = xr[d]; // the PARTIAL rotation's untouched tail
119    for (int i = 0; i < half; ++i) {
120        const size_t toff = (size_t) mrope_pos(mtab, pos[r], i) * half;   // the image path's per-pair position
121        // THE PAIRING AND THE SIGNS COME FROM `rope_neox_pair`, shared with the indexer's pooling kernel.
122        rope_neox_pair(xr[i], xr[half + i], cos_tab[toff + i], sin_tab[toff + i], orow[i], orow[half + i]);
123    }
124}
125
126}  // namespace
127
128void rope_neox_apply(const float* x, float* out, int64_t rows, int head_dim, int n_rot, const float* cos_tab,
129                     const float* sin_tab, const int* pos, void* stream) {
130    if (rows <= 0 || n_rot <= 0) return;
131    if (n_rot % 2 != 0 || n_rot > head_dim) {
132        std::fprintf(stderr, "rope_neox_apply: n_rot %d must be even and <= head_dim %d\n", n_rot, head_dim);
133        std::exit(1);
134    }
135    const int threads = 128;
136    const unsigned grid = (unsigned) ((rows + threads - 1) / threads);
137    {
138        auto exp_props = sycl::ext::oneapi::experimental::properties{
139            sycl::ext::oneapi::experimental::use_root_sync};
140
141        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
142            ->submit([&](sycl::handler &cgh) {
143                auto mrope_table_ct8 = mrope_table();
144
145                cgh.parallel_for<
146                    dpct_kernel_name<class rope_neox_kernel_e291c2>>(
147                    sycl::nd_range<3>(sycl::range(1, 1, grid) *
148                                          sycl::range(1, 1, threads),
149                                      sycl::range(1, 1, threads)),
150                    exp_props, [=](sycl::nd_item<3> item_ct1) {
151                        rope_neox_kernel(x, out, rows, head_dim, n_rot, cos_tab,
152                                         sin_tab, pos, mrope_table_ct8);
153                    });
154            });
155    }
156    /*
157    DPCT1010: SYCL uses exceptions to report errors and does not use the
158    error codes. The cudaGetLastError function call was replaced with 0. You
159    need to rewrite this code.
160    */
161    const dpct::err0 e = 0;
162
163    if (stream == nullptr) dpct::get_current_device().queues_wait_and_throw();
164}
165
166}  // namespace strata::kernels