okami.mom/strata

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

Niko1221perf(rope): fused per-head RMSNorm + RoPE for the verify window and the MTP drafter, off on HIP (#783 PR-f)088e8a822

main
12.4 KiB245 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#include "strata/kernels/native_rope.hpp"
26#include "strata/kernels/mrope.hpp"
27#include <cuda_runtime.h>
28#include <atomic>
29#include <cmath>
30#include <cstdint>
31#include <cstdlib>
32#include <limits>
33#include <stdexcept>
34
35namespace strata::kernels {
36namespace {
37std::atomic<bool> enabled{false};
38bool overlaps(const void* a, size_t an, const void* b, size_t bn) {
39    auto x = reinterpret_cast<uintptr_t>(a), y = reinterpret_cast<uintptr_t>(b);
40    return x <= y ? y - x < an : x - y < bn;
41}
42// TAB (#280, STRATA_ROPE_TABLE=1): the angles from the session's float64 table.  The host launches <false> whenever
43// no table applies - the default - so the default kernel is 0.1.31's code exactly (the table read is not in it;
44// with it merely skipped at run time, the compiled default path changed its results).
45template <bool TAB>
46__global__ void apply(const float* x, float* out, int rows, int width,
47                      int n_rot, float theta_scale, float freq_scale, float corr_low, float corr_high,
48                      float ext_factor, float mscale, const int* positions, const int32_t* mtab, RopeTab rt) {
49    const int row = blockIdx.y;
50    const int pair = blockIdx.x * blockDim.x + threadIdx.x;
51    if (row >= rows || pair >= width / 2) return;
52    const size_t start = size_t(row) * width;
53    if (pair >= n_rot / 2) {
54        if (x != out) {
55            out[start + 2 * pair] = x[start + 2 * pair];
56            out[start + 2 * pair + 1] = x[start + 2 * pair + 1];
57        }
58        return;
59    }
60    float c, s;
61    if (!(TAB && rope_tab_cs(rt, mrope_pos(mtab, positions[row], pair), pair, c, s))) {
62        const float theta_extrap = mrope_pos(mtab, positions[row], pair) * powf(theta_scale, float(pair));
63        rope_scaled_angle(theta_extrap, freq_scale, corr_low, corr_high, ext_factor, mscale, pair, c, s);
64    }
65    const float a = x[start + pair], b = x[start + pair + n_rot / 2];
66    out[start + pair] = a * c - b * s;
67    out[start + pair + n_rot / 2] = a * s + b * c;
68}
69
70template <bool TAB>
71__global__ void norm_rope_kernel(const float* x, int in_stride, const float* __restrict__ gamma, float* out,
72                                 int n_cols, int n_rot, float epsilon, float theta_scale,
73                                 float freq_scale, float corr_low, float corr_high,
74                                 float ext_factor, float mscale, const int* positions,
75                                 const int32_t* mtab, RopeTab rt) {
76    const int tid = threadIdx.x;
77    const int row = blockIdx.x;
78    const float* in_row = x + size_t(row) * in_stride;
79    float* out_row = out + size_t(row) * n_cols;
80    float partial = 0.0f;
81    for (size_t col = tid; col < size_t(n_cols); col += 256) {
82        const float xv = in_row[col];
83        partial += xv * xv;
84    }
85    const int half_rot = n_rot / 2;
86    const float x_tid = tid < n_cols ? in_row[tid] : 0.0f;
87    const float x_hi  = tid < half_rot ? in_row[tid + half_rot] : 0.0f;
88    __shared__ float sums[32];
89#pragma unroll
90    for (int offset = 16; offset; offset >>= 1)
91        partial += __shfl_xor_sync(0xffffffffu, partial, offset, 32);
92    const int lane = tid % 32;
93    if (lane == 0) sums[tid / 32] = partial;
94    __syncthreads();
95    partial = lane < 256 / 32 ? sums[lane] : 0.0f;
96#pragma unroll
97    for (int offset = 16; offset; offset >>= 1)
98        partial += __shfl_xor_sync(0xffffffffu, partial, offset, 32);
99    const float mean = partial / n_cols;
100    const float scale = rsqrtf(mean + epsilon);
101    if (tid >= n_rot && tid < n_cols) {
102        out_row[tid] = (scale * x_tid) * gamma[tid];
103    } else if (tid < half_rot) {
104        const int pair = tid;
105        float a = (scale * x_tid) * gamma[pair];
106        float b = (scale * x_hi) * gamma[pair + half_rot];
107#if defined(__CUDA_ARCH__) && !defined(__HIP_DEVICE_COMPILE__)
108        asm volatile("mov.f32 %0, %1;" : "=f"(a) : "f"(a));
109        asm volatile("mov.f32 %0, %1;" : "=f"(b) : "f"(b));
110#endif
111        float c, s;
112        if (!(TAB && rope_tab_cs(rt, mrope_pos(mtab, positions[row], pair), pair, c, s))) {
113            const float theta_extrap = mrope_pos(mtab, positions[row], pair) * powf(theta_scale, float(pair));
114            rope_scaled_angle(theta_extrap, freq_scale, corr_low, corr_high, ext_factor, mscale, pair, c, s);
115        }
116        float bs = b * s;
117        float bc = b * c;
118#if defined(__CUDA_ARCH__) && !defined(__HIP_DEVICE_COMPILE__)
119        asm volatile("mov.f32 %0, %1;" : "=f"(bs) : "f"(bs));
120        asm volatile("mov.f32 %0, %1;" : "=f"(bc) : "f"(bc));
121#endif
122        out_row[pair] = fmaf(a, c, -bs);
123        out_row[pair + half_rot] = fmaf(a, s, bc);
124    }
125}
126}
127// one table per device (a layer split runs the rope kernels on several): set and read for the current device
128namespace {
129constexpr int kMropeDevices = 64;
130std::atomic<const int32_t*> mrope_tab[kMropeDevices] = {};
131int mrope_dev() {
132    int d = 0;
133    if (cudaGetDevice(&d) != cudaSuccess || d < 0 || d >= kMropeDevices) d = 0;
134    return d;
135}
136}  // namespace
137void mrope_table_set(const int32_t* device_table) { mrope_tab[mrope_dev()].store(device_table, std::memory_order_relaxed); }
138const int32_t* mrope_table() { return mrope_tab[mrope_dev()].load(std::memory_order_relaxed); }
139namespace {
140// #280: the float64 angle table of each device, set at session init (before any graph is captured)
141struct RopeReg {
142    RopeTab tab;
143    RopeScaling scaling;
144};
145RopeReg rope_tab[kMropeDevices] = {};
146bool same_scaling(const RopeScaling& a, const RopeScaling& b) {
147    return a.type == b.type && a.freq_base == b.freq_base && a.factor == b.factor && a.freq_scale_in == b.freq_scale_in &&
148           a.orig_ctx == b.orig_ctx && a.ext_factor == b.ext_factor && a.attn_factor == b.attn_factor &&
149           a.beta_fast == b.beta_fast && a.beta_slow == b.beta_slow;
150}
151// opt-in: STRATA_ROPE_TABLE=1 (the table's angles differ from the fast-math ones in the last bits, so outputs move)
152bool rope_table_enabled() {
153    static const bool on = [] {
154        const char* e = std::getenv("STRATA_ROPE_TABLE");
155        return e != nullptr && e[0] == '1';
156    }();
157    return on;
158}
159}  // namespace
160void rope_table_set(const float* cos_tab, const float* sin_tab, int max_pos, const RopeScaling& scaling) {
161    rope_tab[mrope_dev()] = RopeReg{RopeTab{cos_tab, sin_tab, max_pos}, scaling};
162}
163void rope_table_release(const float* cos_tab) {
164    // every device's entry that points at it (the caller may free it from another current device)
165    for (RopeReg& r : rope_tab)
166        if (cos_tab != nullptr && r.tab.cos == cos_tab) r = RopeReg{};
167}
168RopeTab rope_table_for(const RopeScaling& scaling) {
169    if (!rope_table_enabled()) return {};
170    const RopeReg& r = rope_tab[mrope_dev()];
171    return r.tab.cos != nullptr && same_scaling(r.scaling, scaling) ? r.tab : RopeTab{};
172}
173void native_rope_set_enabled(bool value) { enabled.store(value, std::memory_order_relaxed); }
174bool native_rope_enabled() { return enabled.load(std::memory_order_relaxed); }
175bool native_norm_rope_usable(int head_dim, int n_rot) {
176    static const bool on = [] {
177        const char* off = std::getenv("STRATA_NO_NORM_ROPE");
178        if (off != nullptr && off[0] != '\0' && off[0] != '0') return false;
179#if defined(__HIPCC__)
180        const char* v = std::getenv("STRATA_NORM_ROPE");   // AMD: opt in until rope_parity check 6 passes there
181        return v != nullptr && v[0] != '\0' && v[0] != '0';
182#else
183        return true;
184#endif
185    }();
186    return on && (head_dim == 128 || head_dim == 256) && n_rot == 64;
187}
188
189void native_rope_apply(const float* x, float* out, int rows, int head_dim,
190                       int n_rot, const RopeScaling& scaling, const int* positions, void* stream) {
191    if (!x || !out || !positions || !stream || rows < 1 || rows > 65535 ||
192        (head_dim != 128 && head_dim != 256) || n_rot != 64 ||
193        rope_scaling_invalid(scaling) != nullptr ||
194        reinterpret_cast<uintptr_t>(x) % 4 || reinterpret_cast<uintptr_t>(out) % 4 ||
195        reinterpret_cast<uintptr_t>(positions) % 4) {
196        throw std::invalid_argument("native RoPE requires aligned F32 rows, width 128/256, rotation 64, valid base/scaling and explicit stream");
197    }
198    const size_t bytes = size_t(rows) * head_dim * sizeof(float);
199    if ((x != out && overlaps(x, bytes, out, bytes)) ||
200        overlaps(positions, size_t(rows) * sizeof(int), out, bytes) ||
201        overlaps(positions, size_t(rows) * sizeof(int), x, bytes)) {
202        throw std::invalid_argument("native RoPE buffers partially overlap");
203    }
204    // Match pinned host-side float powf before device fast powf/trigonometry.
205    const float theta_scale = powf((float) scaling.freq_base, -2.0f / n_rot);
206    const RopeKernelArgs k = scaling.kernel_args(n_rot);   // none: the identity constants
207    const RopeTab rt = rope_table_for(scaling);
208    const unsigned threads = (x == out && n_rot == 64 && native_norm_rope_usable(head_dim, n_rot)) ? 32u : 128u;
209    const dim3 grid(threads == 32u ? 1u : unsigned((head_dim / 2 + 127) / 128), rows);
210    if (rt.cos != nullptr)
211        apply<true><<<grid, threads, 0, static_cast<cudaStream_t>(stream)>>>(x, out, rows, head_dim, n_rot, theta_scale,
212            k.freq_scale, k.corr_low, k.corr_high, k.ext_factor, k.attn_factor, positions, mrope_table(), rt);
213    else
214        apply<false><<<grid, threads, 0, static_cast<cudaStream_t>(stream)>>>(x, out, rows, head_dim, n_rot, theta_scale,
215            k.freq_scale, k.corr_low, k.corr_high, k.ext_factor, k.attn_factor, positions, mrope_table(), rt);
216    const auto error = cudaGetLastError();
217    if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error));
218}
219
220void native_qsa_rms_norm_rope(const float* x, int in_stride, const float* gamma, float* out,
221                              int rows, int head_dim, int n_rot, float epsilon,
222                              const RopeScaling& scaling, const int* positions, void* stream) {
223    if (!x || !gamma || !out || !positions || !stream || rows < 1 || rows > 65535 ||
224        (head_dim != 128 && head_dim != 256) || in_stride < head_dim || n_rot != 64 ||
225        !std::isfinite(epsilon) || epsilon < 0.0f ||
226        rope_scaling_invalid(scaling) != nullptr ||
227        reinterpret_cast<uintptr_t>(x) % 4 || reinterpret_cast<uintptr_t>(gamma) % 4 ||
228        reinterpret_cast<uintptr_t>(out) % 4 || reinterpret_cast<uintptr_t>(positions) % 4) {
229        throw std::invalid_argument("native_qsa_rms_norm_rope: invalid arguments");
230    }
231    const float theta_scale = powf((float) scaling.freq_base, -2.0f / n_rot);
232    const RopeKernelArgs k = scaling.kernel_args(n_rot);
233    const RopeTab rt = rope_table_for(scaling);
234    if (rt.cos != nullptr)
235        norm_rope_kernel<true><<<unsigned(rows), 256, 0, static_cast<cudaStream_t>(stream)>>>(
236            x, in_stride, gamma, out, head_dim, n_rot, epsilon, theta_scale,
237            k.freq_scale, k.corr_low, k.corr_high, k.ext_factor, k.attn_factor, positions, mrope_table(), rt);
238    else
239        norm_rope_kernel<false><<<unsigned(rows), 256, 0, static_cast<cudaStream_t>(stream)>>>(
240            x, in_stride, gamma, out, head_dim, n_rot, epsilon, theta_scale,
241            k.freq_scale, k.corr_low, k.corr_high, k.ext_factor, k.attn_factor, positions, mrope_table(), rt);
242    const auto error = cudaGetLastError();
243    if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error));
244}
245}