okami.mom/strata

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

Niko1221Merge f-84 into rel-0.1.3012ebc6727

main
6.9 KiB136 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#include "strata/kernels/rope.hpp"
29#include "strata/kernels/mrope.hpp"
30
31#include <cuda_runtime.h>
32
33#include <cmath>
34#include <cstdio>
35#include <cstdlib>
36
37namespace strata::kernels {
38
39namespace {
40// The process's rope config (rope_scaling.hpp).  One writer - the engine's startup thread, before
41// session_init builds any table or captures any graph - and readers after it.
42RopeScaling g_rope_scaling;
43}  // namespace
44
45void rope_scaling_set(const RopeScaling& scaling) { g_rope_scaling = scaling; }
46const RopeScaling& rope_scaling() { return g_rope_scaling; }
47
48void build_rope_table(int n_rot, double theta, int max_pos, float* cos_tab, float* sin_tab) {
49    const int half = n_rot / 2;
50    for (int p = 0; p < max_pos; ++p) {
51        for (int i = 0; i < half; ++i) {
52            // float64 throughout, in the reference's order: inv, then ang, then cos/sin
53            const double inv = std::pow(theta, -2.0 * (double) i / (double) n_rot);
54            const double ang = (double) p * inv;
55            cos_tab[(size_t) p * half + i] = (float) std::cos(ang);
56            sin_tab[(size_t) p * half + i] = (float) std::sin(ang);
57        }
58    }
59}
60
61void build_rope_table(int n_rot, const RopeScaling& sc, int max_pos, float* cos_tab, float* sin_tab) {
62    if (sc.type == RopeScalingType::None) {
63        build_rope_table(n_rot, sc.freq_base, max_pos, cos_tab, sin_tab);   // the original loop, verbatim
64        return;
65    }
66    const int half = n_rot / 2;
67    const double fs = sc.freq_scale();
68    const double ms = sc.mscale();
69    double cd[2];
70    sc.corr_dims(n_rot, cd);
71    const bool correct = sc.ext_factor != 0;   // ggml: the correction rides on ext_factor, not the type
72    for (int p = 0; p < max_pos; ++p) {
73        for (int i = 0; i < half; ++i) {
74            const double inv = std::pow(sc.freq_base, -2.0 * (double) i / (double) n_rot);
75            const double extrap = (double) p * inv;    // the trained angle, ggml's theta_extrap
76            const double interp = fs * extrap;         // ggml's theta_interp
77            double ang = interp;
78            if (correct) {
79                const double ramp = (double) rope_yarn_ramp((float) cd[0], (float) cd[1], i) * sc.ext_factor;
80                ang = interp * (1.0 - ramp) + extrap * ramp;
81            }
82            cos_tab[(size_t) p * half + i] = (float) (std::cos(ang) * ms);
83            sin_tab[(size_t) p * half + i] = (float) (std::sin(ang) * ms);
84        }
85    }
86}
87
88namespace {
89
90// ONE THREAD PER ROW, not per (row, pair).  The first version had one thread per pair and did the tail copy
91// with 	hreadIdx.x strided loops - so up to 32 threads wrote into the SAME row, with no barrier between the
92// copy and the rotation, and a thread's copy of orow[i] could land AFTER another thread had rotated it.  A
93// race that silently writes the unrotated value is worse than a wrong answer: it is intermittent.
94//
95// A row is head_dim floats (256 here) and there are batch x heads of them, so one thread per row is a
96// handful of threads for a token and removes the ordering question entirely rather than synchronising it.
97__global__ void rope_neox_kernel(const float* __restrict__ x, float* __restrict__ out, long long rows,
98                                 int head_dim, int n_rot, const float* __restrict__ cos_tab,
99                                 const float* __restrict__ sin_tab, const int* __restrict__ pos,
100                                 const int32_t* __restrict__ mtab) {
101    const long long r = (long long) blockIdx.x * blockDim.x + threadIdx.x;
102    if (r >= rows) return;
103    const int half = n_rot / 2;
104    const float* xr = x + r * head_dim;
105    float* orow = out + r * head_dim;
106
107    for (int d = n_rot; d < head_dim; ++d) orow[d] = xr[d];      // the PARTIAL rotation's untouched tail
108    for (int i = 0; i < half; ++i) {
109        const size_t toff = (size_t) mrope_pos(mtab, pos[r], i) * half;   // the image path's per-pair position
110        // THE PAIRING AND THE SIGNS COME FROM `rope_neox_pair`, shared with the indexer's pooling kernel.
111        rope_neox_pair(xr[i], xr[half + i], cos_tab[toff + i], sin_tab[toff + i], orow[i], orow[half + i]);
112    }
113}
114
115}  // namespace
116
117void rope_neox_apply(const float* x, float* out, int64_t rows, int head_dim, int n_rot, const float* cos_tab,
118                     const float* sin_tab, const int* pos, void* stream) {
119    if (rows <= 0 || n_rot <= 0) return;
120    if (n_rot % 2 != 0 || n_rot > head_dim) {
121        std::fprintf(stderr, "rope_neox_apply: n_rot %d must be even and <= head_dim %d\n", n_rot, head_dim);
122        std::exit(1);
123    }
124    const int threads = 128;
125    const unsigned grid = (unsigned) ((rows + threads - 1) / threads);
126    rope_neox_kernel<<<grid, threads, 0, (cudaStream_t) stream>>>(x, out, rows, head_dim, n_rot, cos_tab,
127                                                                 sin_tab, pos, mrope_table());
128    const cudaError_t e = cudaGetLastError();
129    if (e != cudaSuccess) {
130        std::fprintf(stderr, "rope_neox_apply launch: %s\n", cudaGetErrorString(e));
131        std::exit(1);
132    }
133    if (stream == nullptr) cudaDeviceSynchronize();
134}
135
136}  // namespace strata::kernels