diff --git a/include/strata/kernels/native_qsa_indexer.hpp b/include/strata/kernels/native_qsa_indexer.hpp index 560b12b5be..fe66d4b06f 100644 --- a/include/strata/kernels/native_qsa_indexer.hpp +++ b/include/strata/kernels/native_qsa_indexer.hpp @@ -1,5 +1,6 @@ #pragma once #include "strata/kernels/qsa.hpp" +#include "strata/kernels/rope_scaling.hpp" namespace strata::kernels { @@ -20,6 +21,9 @@ bool native_qsa_indexer_enabled(); // contiguous, with nonnegative pos_base divisible by four. Clear state before // starting a new sequence. Completed block b rotates at pos_base+4*b; the spare // always rotates at zero, including nonzero sequence bases, as in the oracle. +// Under rope scaling (rope_scaling.hpp) the zero angle keeps the spare's +// rotation an identity; YaRN's mscale rides in through cos(0) on both the pooled +// keys and the indexer queries, so selection is unchanged. // // Explicit nonnull stream; no allocation or synchronization. All spans must be // aligned and disjoint, remain valid through replay, and contain finite values; @@ -32,11 +36,11 @@ bool native_qsa_indexer_enabled(); // Host-side positions (not for a captured graph). void native_qsa_indexer_append_batch(const float* raw, int64_t n, int64_t p0, int32_t pos_base, const float* gamma, float epsilon, const QsaIndexerBuffers& b, const QsaShapes& s, int64_t max_cells, - float freq_base, void* stream); + const RopeScaling& scaling, void* stream); void native_qsa_indexer_append(const float* raw, const int32_t* relative_pos_device, int32_t pos_base, const float* gamma, float epsilon, const QsaIndexerBuffers& buffers, const QsaShapes& shapes, - int64_t max_cells, float freq_base, void* stream); + int64_t max_cells, const RopeScaling& scaling, void* stream); } // namespace strata::kernels diff --git a/include/strata/kernels/native_rope.hpp b/include/strata/kernels/native_rope.hpp index 24bffe61e6..95511b88c2 100644 --- a/include/strata/kernels/native_rope.hpp +++ b/include/strata/kernels/native_rope.hpp @@ -1,14 +1,20 @@ #pragma once +#include "strata/kernels/rope_scaling.hpp" + namespace strata::kernels { void native_rope_set_enabled(bool enabled); bool native_rope_enabled(); -// Pinned CUDA text-only IMRoPE: F32 rows, 64 rotated channels, no YaRN/frequency -// factors, equal text positions in all four IMRoPE sections. Each device position -// must be nonnegative. The position buffer remains live through graph replay. -// Supports head_dim 128/256 and exact x==out; partial overlap is rejected. +// Pinned CUDA text-only IMRoPE: F32 rows, 64 rotated channels, equal text positions in all four +// IMRoPE sections. Each device position must be nonnegative. The position buffer remains live +// through graph replay. Supports head_dim 128/256 and exact x==out; partial overlap is rejected. // Explicit stream required. No allocation or synchronization. +// +// The scaling (rope_scaling.hpp) rides in as the resolved process config: none reproduces the +// original contract exactly, linear/YaRN apply ggml's rope_yarn - the interpolation mix, the +// corr_dims ramp along the pairs, and the mscale magnitude correction folded into cos and sin. +// The struct's knobs are process constants, so kernel arguments baked at graph capture stay valid. void native_rope_apply(const float* x, float* out, int rows, int head_dim, - int n_rot, float freq_base, const int* positions, void* stream); + int n_rot, const RopeScaling& scaling, const int* positions, void* stream); } diff --git a/include/strata/kernels/qsa.hpp b/include/strata/kernels/qsa.hpp index e6090abf2f..dc26024ad5 100644 --- a/include/strata/kernels/qsa.hpp +++ b/include/strata/kernels/qsa.hpp @@ -118,7 +118,10 @@ inline QsaShapes qsa_real_shapes() { /// The one legal RMSNorm epsilon for this artifact (`attention.layer_norm_rms_epsilon`). inline float qsa_rms_eps() { return 1e-6f; } -/// `rope.freq_base`, no rope.scaling keys, so freq_scale = 1 and no YaRN. +/// `rope.freq_base`, the DEFAULT frequency base. The artifact ships no `rope.scaling` keys, so the +/// process's rope scaling starts at none - the runtime configuration lives in `rope_scaling.hpp` +/// (`rope_scaling_set`, once at startup, before the table is built and any graph captured), and this +/// constant is what that config's `freq_base` defaults to and what CLI `--rope-freq-base` overrides. inline double qsa_freq_base() { return 1e7; } /// The selection width: `min(n_kv, idx_top_k + idx_block - 1)`. diff --git a/include/strata/prefill/kernels.hpp b/include/strata/prefill/kernels.hpp index f425694522..3a4d1ca680 100644 --- a/include/strata/prefill/kernels.hpp +++ b/include/strata/prefill/kernels.hpp @@ -6,6 +6,7 @@ #pragma once #include "strata/kernels/kv_stream.hpp" +#include "strata/kernels/rope_scaling.hpp" #include @@ -65,8 +66,10 @@ void moe_combine(const float* D, const int32_t* slot, const float* w, const floa // ---- QSA helpers /// In place: x[r, :] = x[r, :] * rsqrt(mean x^2 + eps) * w over rows of `cols` (row stride `ld`). void rms_rows(float* x, const float* w, int64_t rows, int64_t cols, int64_t ld, float eps, void* stream); -/// NEOX rotary on the first 64 dims of each head: x [T, heads, dim] at positions pos0 + t. -void rope(float* x, int64_t T, int64_t heads, int64_t dim, int64_t ld, int64_t pos0, float freq_base, void* stream); +/// NEOX rotary on the first 64 dims of each head: x [T, heads, dim] at positions pos0 + t. The rope +/// scaling (rope_scaling.hpp) rides in as the process config - none is today's arithmetic exactly. +void rope(float* x, int64_t T, int64_t heads, int64_t dim, int64_t ld, int64_t pos0, + const strata::kernels::RopeScaling& scaling, void* stream); /// q_full [T, 24, 512] (q | gate per head) -> q [T, 24, 256] void split_q(const float* q_full, float* q, int64_t T, void* stream); /// attn[t, h, d] *= sigmoid(q_full[t, h, 256 + d]) -> out16 (fp16 bits: the o-projection is quantized) diff --git a/src/core/layer.cpp b/src/core/layer.cpp index 5c6c06ef11..8ad9f41aaa 100644 --- a/src/core/layer.cpp +++ b/src/core/layer.cpp @@ -655,9 +655,10 @@ uint64_t qsa_state_init(const ModelGeometry& g, int64_t max_cells, void* base, Q // THE ROPE TABLE IS BUILT ON THE HOST IN FLOAT64 and uploaded once, because the reference computes its // frequencies in float64 and reproducing that on device means double-precision `pow`/`cos` that need not // agree with the host's libm. A table shorter than the sequence would have the rotation read past it. + // The process's rope scaling (none by default) is INSIDE the table - the rotation kernels cannot tell. if (share_rope == nullptr) { std::vector hc((size_t) max_cells * (s.n_rot / 2)), hs((size_t) max_cells * (s.n_rot / 2)); - strata::kernels::build_rope_table((int) s.n_rot, strata::kernels::qsa_freq_base(), (int) max_cells, + strata::kernels::build_rope_table((int) s.n_rot, strata::kernels::rope_scaling(), (int) max_cells, hc.data(), hs.data()); cudaMemcpy(st.cos_tab, hc.data(), hc.size() * 4, cudaMemcpyHostToDevice); cudaMemcpy(st.sin_tab, hs.data(), hs.size() * 4, cudaMemcpyHostToDevice); @@ -843,7 +844,7 @@ const auto normalize_rotate = [&](float* data, const WeightRef* norm, int rows, try { if (native_qsa_enabled()) native_qsa_rms_norm_weighted(data, (const float*) norm->data, data, cols, rows, RMS_EPS, stream); else rms_norm_weighted(data, (const float*) norm->data, rows, cols, RMS_EPS, stream); - if (native_rope_enabled()) native_rope_apply(data, data, rows, cols, (int) s.n_rot, (float) qsa_freq_base(), st.pos_dev, stream); + if (native_rope_enabled()) native_rope_apply(data, data, rows, cols, (int) s.n_rot, rope_scaling(), st.pos_dev, stream); else rope_neox_apply(data, data, rows, cols, (int) s.n_rot, st.cos_tab, st.sin_tab, st.pos_dev, stream); return true; } catch (const std::exception& error) { @@ -905,7 +906,7 @@ if (st.kv_hybrid) { } else if (st.kv_int8) kv_append_q8_step(st.k_q, st.v_q, st.k_scale, st.v_scale, st.page_table, st.step, b.kcur, b.vcur, s, stream, &st.host); else kv_append_step(st.k_pool, st.v_pool, st.page_table, st.step, b.kcur, b.vcur, s, stream, &st.host); { const uint64_t nvk = (uint64_t) g.n_head_kv * g.head_dim; const uint64_t base = (uint64_t) 2 * g.n_embd + 2 * g.hc + (uint64_t) g.n_head * g.head_dim + 2 * nvk + 8; if (!st.kv_int8 && !st.kv_hybrid) dump_slot(dump, g, layer, (const float*) st.k_pool, base, nvk / 2, stream); if (!st.kv_int8 && !st.kv_hybrid) dump_slot(dump, g, layer, (const float*) st.v_pool, base + nvk / 2, nvk / 2, stream); dump_slot(dump, g, layer, b.vcur, base + nvk, nvk, stream); dump_slot(dump, g, layer, b.kcur, base + 2 * nvk, nvk, stream); } { const QsaIndexerBuffers ib{st.idx_tail, st.idx_dead, st.idx_pooled, st.idx_block_pos}; if (native_qsa_indexer_enabled()) { try { native_qsa_indexer_append(b.idx_raw, st.step + kStepPos, pos_base, - (const float*) w_ikn->data, RMS_EPS, ib, s, st.max_cells, (float) qsa_freq_base(), stream); + (const float*) w_ikn->data, RMS_EPS, ib, s, st.max_cells, rope_scaling(), stream); } catch (const std::exception& error) { err = v.name("native_indexer") + ": " + error.what(); return false; } } else indexer_key_append(b.idx_raw, st.pos_dev, pos_base, (const float*) w_ikn->data, RMS_EPS, ib, s, st.cos_tab, st.sin_tab, stream); } diff --git a/src/core/mtp.cpp b/src/core/mtp.cpp index 2b1d79ef8a..a53c60e254 100644 --- a/src/core/mtp.cpp +++ b/src/core/mtp.cpp @@ -395,7 +395,7 @@ bool MtpDrafter::record_forward(int T, int step_row0, cudaStream_t cs, std::stri // ---- attention: K/V into the layer's own cache, then (full) dense attention over every cell auto norm_rope = [&](float* data, const float* gamma, int rows, int cols, const int32_t* p) { native_qsa_rms_norm_weighted(data, gamma, data, cols, rows, EPS, cs); - if (native_rope_enabled()) native_rope_apply(data, data, rows, cols, (int) s.n_rot, (float) qsa_freq_base(), p, cs); + if (native_rope_enabled()) native_rope_apply(data, data, rows, cols, (int) s.n_rot, rope_scaling(), p, cs); else rope_neox_apply(data, data, rows, cols, (int) s.n_rot, st_.cos_tab, st_.sin_tab, p, cs); }; native_quantize_q8_1(mixed_, xq_, (int) N, T, cs); diff --git a/src/core/verify.cpp b/src/core/verify.cpp index 085135a95f..e461ca5ea5 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -492,7 +492,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { auto norm_rope = [&](float* data, const WeightRef* norm, int rows, int cols, const int32_t* pos) { if (native_qsa_enabled()) native_qsa_rms_norm_weighted(data, (const float*) norm->data, data, cols, rows, EPS, cs); else rms_norm_weighted(data, (const float*) norm->data, rows, cols, EPS, cs); - if (native_rope_enabled()) native_rope_apply(data, data, rows, cols, (int) s.n_rot, (float) qsa_freq_base(), pos, cs); + if (native_rope_enabled()) native_rope_apply(data, data, rows, cols, (int) s.n_rot, rope_scaling(), pos, cs); else rope_neox_apply(data, data, rows, cols, (int) s.n_rot, st.cos_tab, st.sin_tab, pos, cs); }; float* idx_raw = idx_raw_L_ + (size_t) qi * MT * ID; @@ -537,7 +537,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { for (int t = tb; t < te; ++t) native_qsa_indexer_append(idx_raw + t * ID, step_ + t * kStepCount + kStepPos, 0, (const float*) wikn->data, EPS, ib, s, st.max_cells, - (float) qsa_freq_base(), cs); + rope_scaling(), cs); stamp(l, 9, grp); native_mmvq(wq->native_type, wq->native_data, xq_, qfull_ + tb * NH * 2 * HD, (int) N, (int) (NH * 2 * HD), n, cs); @@ -923,7 +923,7 @@ bool Verifier::capture_commit(std::string& err) { for (int64_t t = 0; t < MT; ++t) native_qsa_indexer_append(idx_raw_L_ + (size_t) (qsa_index * MT + t) * ID, commit_ + 2 + t, 0, (const float*) wikn->data, EPS, ib, s, st.max_cells, - (float) qsa_freq_base(), cs_); + rope_scaling(), cs_); ++qsa_index; } } diff --git a/src/kernels/cuda/native_qsa_indexer.cu b/src/kernels/cuda/native_qsa_indexer.cu index 8a5ecbc3c9..86d6ae835a 100644 --- a/src/kernels/cuda/native_qsa_indexer.cu +++ b/src/kernels/cuda/native_qsa_indexer.cu @@ -43,7 +43,9 @@ __global__ void append(const float* __restrict__ raw, const int32_t* __restrict_ int pos_base, const float* __restrict__ gamma, float epsilon, float* __restrict__ tail, float* __restrict__ dead, float* __restrict__ pooled, int32_t* __restrict__ block_pos, - int max_cells, float theta_scale, const int32_t* __restrict__ mtab) { + int max_cells, float theta_scale, float freq_scale, float corr_low, + float corr_high, float ext_factor, float mscale, + const int32_t* __restrict__ mtab) { const int pos = *pos_dev, d = threadIdx.x; if (pos < 0 || pos >= max_cells) return; const int slot = pos % R; @@ -83,8 +85,11 @@ __global__ void append(const float* __restrict__ raw, const int32_t* __restrict_ float y = values[d]; if (d < ROT) { const int pair = d % (ROT / 2); - const float theta = (pos == 0 ? 0 : mrope_pos(mtab, rope_pos, pair)) * powf(theta_scale, float(pair)); - const float c = cosf(theta), s = sinf(theta); + // The spare (pos == 0) keeps its zero angle; under YaRN the mscale magnitude still rides in + // through cos(0) - which is exactly what the queries are scaled by, so the top-k is unmoved. + const float theta_extrap = (pos == 0 ? 0 : mrope_pos(mtab, rope_pos, pair)) * powf(theta_scale, float(pair)); + float c, s; + rope_scaled_angle(theta_extrap, freq_scale, corr_low, corr_high, ext_factor, mscale, pair, c, s); const float a = values[pair], z = values[pair + ROT / 2]; y = d < ROT / 2 ? a * c - z * s : a * s + z * c; } @@ -99,12 +104,17 @@ __global__ void append(const float* __restrict__ raw, const int32_t* __restrict_ // (cell >= p0) or the tail the previous batch left (cell < p0). Only the batch's last completed block writes the // spare after it (every earlier one's is overwritten by the next block in order). __device__ __forceinline__ float pooled_value(const float* values, int d, int rope_pos, float theta_scale, - const int32_t* mtab, bool zero_pos) { + float freq_scale, float corr_low, float corr_high, + float ext_factor, float mscale, const int32_t* mtab, bool zero_pos) { float y = values[d]; if (d < ROT) { const int pair = d % (ROT / 2); - const float theta = (zero_pos ? 0 : mrope_pos(mtab, rope_pos, pair)) * powf(theta_scale, float(pair)); - const float c = cosf(theta), s = sinf(theta); + // The same rotation the single append applies, rope_scaling.hpp's helper shared: under none this is + // today's cosf/sinf; under linear/YaRN the pooled keys move with the cache's K, and the spare's zero + // angle carries the mscale magnitude through cos(0) exactly as the single append's does. + const float theta_extrap = (zero_pos ? 0 : mrope_pos(mtab, rope_pos, pair)) * powf(theta_scale, float(pair)); + float c, s; + rope_scaled_angle(theta_extrap, freq_scale, corr_low, corr_high, ext_factor, mscale, pair, c, s); const float a = values[pair], z = values[pair + ROT / 2]; y = d < ROT / 2 ? a * c - z * s : a * s + z * c; } @@ -123,6 +133,7 @@ __device__ __forceinline__ float norm_scale(float mean, float* partials, int d) // cell 0 of a sequence: the spare (every gather index names cell 0), written to pooled[0] and dead __global__ void append_first(const float* __restrict__ raw, const float* __restrict__ gamma, float epsilon, float* __restrict__ dead, float* __restrict__ pooled, float theta_scale, + float freq_scale, float corr_low, float corr_high, float ext_factor, float mscale, const int32_t* __restrict__ mtab) { const int d = threadIdx.x; __shared__ float values[D]; @@ -140,14 +151,17 @@ __global__ void append_first(const float* __restrict__ raw, const float* __restr if (d < D) values[d] = scale * mean * gamma[d]; __syncthreads(); if (d >= D) return; - const float y = pooled_value(values, d, 0, theta_scale, mtab, true); + const float y = pooled_value(values, d, 0, theta_scale, freq_scale, corr_low, corr_high, ext_factor, mscale, + mtab, true); pooled[d] = y; dead[d] = y; } __global__ void append_blocks(const float* __restrict__ raw, int64_t n, int64_t p0, int pos_base, const float* __restrict__ gamma, float epsilon, const float* __restrict__ tail, const float* __restrict__ dead, float* __restrict__ pooled, int32_t* __restrict__ block_pos, - int64_t first_block, int64_t last_block, float theta_scale, const int32_t* __restrict__ mtab) { + int64_t first_block, int64_t last_block, float theta_scale, float freq_scale, + float corr_low, float corr_high, float ext_factor, float mscale, + const int32_t* __restrict__ mtab) { const int64_t b = first_block + blockIdx.x; const int d = threadIdx.x; __shared__ float values[D]; @@ -169,7 +183,8 @@ __global__ void append_blocks(const float* __restrict__ raw, int64_t n, int64_t __syncthreads(); if (d >= D) return; const int rope_pos = pos_base + R * (int) b; - pooled[std::size_t(b) * D + d] = pooled_value(values, d, rope_pos, theta_scale, mtab, false); + pooled[std::size_t(b) * D + d] = pooled_value(values, d, rope_pos, theta_scale, freq_scale, corr_low, corr_high, + ext_factor, mscale, mtab, false); if (b == last_block) { pooled[std::size_t(b + 1) * D + d] = dead[d]; if (d == 0) *block_pos = rope_pos; @@ -200,42 +215,65 @@ void native_qsa_indexer_set_enabled(bool value) { enabled.store(value, std::memo bool native_qsa_indexer_enabled() { return enabled.load(std::memory_order_relaxed); } void native_qsa_indexer_append(const float* raw, const int32_t* relative_pos_device, int32_t pos_base, const float* gamma, float epsilon, const QsaIndexerBuffers& b, - const QsaShapes& s, int64_t max_cells, float freq_base, void* stream) { + const QsaShapes& s, int64_t max_cells, const RopeScaling& scaling, void* stream) { + const double fs = scaling.freq_scale(); if (!stream || s.idx_dim != D || s.idx_block != R || s.n_rot != ROT || max_cells < 1 || max_cells > INT32_MAX || pos_base < 0 || pos_base % R || int64_t(pos_base) + max_cells > INT32_MAX || !std::isfinite(epsilon) || epsilon <= 0.0f || - !std::isfinite(freq_base) || freq_base <= 1.0f) - throw std::invalid_argument("native QSA indexer requires fixed geometry, aligned position base, positive capacity/epsilon, valid frequency and explicit stream"); + !std::isfinite(scaling.freq_base) || scaling.freq_base <= 1.0 || + !std::isfinite(fs) || fs <= 0.0 || + !std::isfinite(scaling.ext_factor) || scaling.ext_factor < 0.0 || + !std::isfinite(scaling.attn_factor) || scaling.attn_factor <= 0.0 || + !std::isfinite(scaling.orig_ctx) || scaling.orig_ctx < 1.0 || + !std::isfinite(scaling.beta_fast) || scaling.beta_fast <= 0.0 || + !std::isfinite(scaling.beta_slow) || scaling.beta_slow <= 0.0) + throw std::invalid_argument("native QSA indexer requires fixed geometry, aligned position base, positive capacity/epsilon, valid frequency/scaling and explicit stream"); const Span spans[] = {{raw,D*4},{relative_pos_device,4},{gamma,D*4},{b.tail,(R-1)*D*4}, {b.dead,D*4},{b.pooled,std::size_t(max_cells/R+1)*D*4},{b.block_pos,4}}; for (const auto& span : spans) validate(span); for (int i = 0; i < 7; ++i) for (int j = i + 1; j < 7; ++j) if (overlaps(spans[i], spans[j])) throw std::invalid_argument("native QSA indexer buffers overlap"); - const float theta_scale = powf(freq_base, -2.0f / ROT); + const float theta_scale = powf((float) scaling.freq_base, -2.0f / ROT); + double corr[2]; + scaling.corr_dims(ROT, corr); append<<<1,THREADS,0,static_cast(stream)>>>(raw,relative_pos_device,pos_base,gamma,epsilon, - b.tail,b.dead,b.pooled,b.block_pos,int(max_cells),theta_scale,mrope_table()); + b.tail,b.dead,b.pooled,b.block_pos,int(max_cells),theta_scale,(float) fs, + (float) corr[0],(float) corr[1],(float) scaling.ext_factor,(float) scaling.attn_factor,mrope_table()); const auto error = cudaGetLastError(); if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error)); } void native_qsa_indexer_append_batch(const float* raw, int64_t n, int64_t p0, int32_t pos_base, const float* gamma, float epsilon, const QsaIndexerBuffers& b, const QsaShapes& s, int64_t max_cells, - float freq_base, void* stream) { + const RopeScaling& scaling, void* stream) { + const double fs = scaling.freq_scale(); if (n <= 0) return; if (!stream || s.idx_dim != D || s.idx_block != R || s.n_rot != ROT || p0 < 0 || p0 + n > max_cells || max_cells > INT32_MAX || pos_base < 0 || pos_base % R || int64_t(pos_base) + max_cells > INT32_MAX || - !std::isfinite(epsilon) || epsilon <= 0.0f || !std::isfinite(freq_base) || freq_base <= 1.0f) - throw std::invalid_argument("native QSA indexer (batch): bad geometry, positions or parameters"); - const float theta_scale = powf(freq_base, -2.0f / ROT); + !std::isfinite(epsilon) || epsilon <= 0.0f || + !std::isfinite(scaling.freq_base) || scaling.freq_base <= 1.0 || + !std::isfinite(fs) || fs <= 0.0 || + !std::isfinite(scaling.ext_factor) || scaling.ext_factor < 0.0 || + !std::isfinite(scaling.attn_factor) || scaling.attn_factor <= 0.0 || + !std::isfinite(scaling.orig_ctx) || scaling.orig_ctx < 1.0 || + !std::isfinite(scaling.beta_fast) || scaling.beta_fast <= 0.0 || + !std::isfinite(scaling.beta_slow) || scaling.beta_slow <= 0.0) + throw std::invalid_argument("native QSA indexer (batch): bad geometry, positions, parameters or scaling"); + const float theta_scale = powf((float) scaling.freq_base, -2.0f / ROT); + double corr[2]; + scaling.corr_dims(ROT, corr); + const float fsf = (float) fs, cl = (float) corr[0], ch = (float) corr[1]; + const float ef = (float) scaling.ext_factor, ms = (float) scaling.attn_factor; const cudaStream_t st = static_cast(stream); const int32_t* mtab = mrope_table(); - if (p0 == 0) append_first<<<1, THREADS, 0, st>>>(raw, gamma, epsilon, b.dead, b.pooled, theta_scale, mtab); + if (p0 == 0) append_first<<<1, THREADS, 0, st>>>(raw, gamma, epsilon, b.dead, b.pooled, theta_scale, + fsf, cl, ch, ef, ms, mtab); // completed blocks: those whose last cell (4b+3) lies in [p0, p0 + n) const int64_t first = p0 <= R - 1 ? 0 : (p0 - (R - 1) + R - 1) / R; // the smallest b with 4b+3 >= p0 const int64_t hi = p0 + n - 1 >= R - 1 ? (p0 + n - 1 - (R - 1)) / R : -1; // the largest b with 4b+3 <= p0+n-1 if (hi >= first) append_blocks<<<(unsigned) (hi - first + 1), THREADS, 0, st>>>(raw, n, p0, pos_base, gamma, epsilon, b.tail, b.dead, b.pooled, b.block_pos, first, hi, - theta_scale, mtab); + theta_scale, fsf, cl, ch, ef, ms, mtab); append_tail<<>>(raw, n, p0, b.tail); const auto error = cudaGetLastError(); if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error)); diff --git a/src/kernels/cuda/native_rope.cu b/src/kernels/cuda/native_rope.cu index 6dd3f6b590..d40c4f6bed 100644 --- a/src/kernels/cuda/native_rope.cu +++ b/src/kernels/cuda/native_rope.cu @@ -39,7 +39,8 @@ bool overlaps(const void* a, size_t an, const void* b, size_t bn) { return x <= y ? y - x < an : x - y < bn; } __global__ void apply(const float* x, float* out, int rows, int width, - int n_rot, float theta_scale, const int* positions, const int32_t* mtab) { + int n_rot, float theta_scale, float freq_scale, float corr_low, float corr_high, + float ext_factor, float mscale, const int* positions, const int32_t* mtab) { const int row = blockIdx.y; const int pair = blockIdx.x * blockDim.x + threadIdx.x; if (row >= rows || pair >= width / 2) return; @@ -51,8 +52,9 @@ __global__ void apply(const float* x, float* out, int rows, int width, } return; } - const float theta = mrope_pos(mtab, positions[row], pair) * powf(theta_scale, float(pair)); - const float c = cosf(theta), s = sinf(theta); + const float theta_extrap = mrope_pos(mtab, positions[row], pair) * powf(theta_scale, float(pair)); + float c, s; + rope_scaled_angle(theta_extrap, freq_scale, corr_low, corr_high, ext_factor, mscale, pair, c, s); const float a = x[start + pair], b = x[start + pair + n_rot / 2]; out[start + pair] = a * c - b * s; out[start + pair + n_rot / 2] = a * s + b * c; @@ -73,13 +75,20 @@ const int32_t* mrope_table() { return mrope_tab[mrope_dev()].load(std::memory_or void native_rope_set_enabled(bool value) { enabled.store(value, std::memory_order_relaxed); } bool native_rope_enabled() { return enabled.load(std::memory_order_relaxed); } void native_rope_apply(const float* x, float* out, int rows, int head_dim, - int n_rot, float freq_base, const int* positions, void* stream) { + int n_rot, const RopeScaling& scaling, const int* positions, void* stream) { + const double fs = scaling.freq_scale(); if (!x || !out || !positions || !stream || rows < 1 || rows > 65535 || (head_dim != 128 && head_dim != 256) || n_rot != 64 || - !std::isfinite(freq_base) || freq_base <= 1.0f || + !std::isfinite(scaling.freq_base) || scaling.freq_base <= 1.0 || + !std::isfinite(fs) || fs <= 0.0 || + !std::isfinite(scaling.ext_factor) || scaling.ext_factor < 0.0 || + !std::isfinite(scaling.attn_factor) || scaling.attn_factor <= 0.0 || + !std::isfinite(scaling.orig_ctx) || scaling.orig_ctx < 1.0 || + !std::isfinite(scaling.beta_fast) || scaling.beta_fast <= 0.0 || + !std::isfinite(scaling.beta_slow) || scaling.beta_slow <= 0.0 || reinterpret_cast(x) % 4 || reinterpret_cast(out) % 4 || reinterpret_cast(positions) % 4) { - throw std::invalid_argument("native RoPE requires aligned F32 rows, width 128/256, rotation 64, valid base and explicit stream"); + throw std::invalid_argument("native RoPE requires aligned F32 rows, width 128/256, rotation 64, valid base/scaling and explicit stream"); } const size_t bytes = size_t(rows) * head_dim * sizeof(float); if ((x != out && overlaps(x, bytes, out, bytes)) || @@ -88,9 +97,14 @@ void native_rope_apply(const float* x, float* out, int rows, int head_dim, throw std::invalid_argument("native RoPE buffers partially overlap"); } // Match pinned host-side float powf before device fast powf/trigonometry. - const float theta_scale = powf(freq_base, -2.0f / n_rot); + const float theta_scale = powf((float) scaling.freq_base, -2.0f / n_rot); + double corr[2]; + scaling.corr_dims(n_rot, corr); apply<<(stream)>>>(x, out, rows, head_dim, n_rot, theta_scale, positions, mrope_table()); + static_cast(stream)>>>(x, out, rows, head_dim, n_rot, theta_scale, + (float) fs, (float) corr[0], (float) corr[1], + (float) scaling.ext_factor, (float) scaling.attn_factor, + positions, mrope_table()); const auto error = cudaGetLastError(); if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error)); } diff --git a/src/prefill/kernels.cu b/src/prefill/kernels.cu index 50984ec9a2..5e74d6097e 100644 --- a/src/prefill/kernels.cu +++ b/src/prefill/kernels.cu @@ -526,13 +526,17 @@ __global__ void rms_rows_kernel(float* __restrict__ x, const float* __restrict__ for (int64_t c = threadIdx.x; c < cols; c += blockDim.x) r[c] = s * r[c] * w[c]; } __global__ void rope_kernel(float* __restrict__ x, int64_t heads, int64_t dim, int64_t ld, int64_t pos0, - float theta_scale, const int32_t* __restrict__ mtab) { + float theta_scale, float freq_scale, float corr_low, float corr_high, + float ext_factor, float mscale, const int32_t* __restrict__ mtab) { const int64_t row = blockIdx.x; // t * heads + h const int pair = threadIdx.x; // 0..31 const int64_t t = row / heads, h = row % heads; float* p = x + t * ld + h * dim; - const float theta = (float) strata::kernels::mrope_pos(mtab, (int) (pos0 + t), pair) * powf(theta_scale, (float) pair); - const float c = cosf(theta), s = sinf(theta); + const float theta_extrap = + (float) strata::kernels::mrope_pos(mtab, (int) (pos0 + t), pair) * powf(theta_scale, (float) pair); + float c, s; + strata::kernels::rope_scaled_angle(theta_extrap, freq_scale, corr_low, corr_high, ext_factor, mscale, + pair, c, s); const float a = p[pair], b = p[pair + 32]; p[pair] = a * c - b * s; p[pair + 32] = a * s + b * c; @@ -757,9 +761,20 @@ void rms_rows(float* x, const float* w, int64_t rows, int64_t cols, int64_t ld, rms_rows_kernel<<<(unsigned) rows, 256, 0, (cudaStream_t) stream>>>(x, w, cols, ld, eps); check("rms_rows"); } -void rope(float* x, int64_t T, int64_t heads, int64_t dim, int64_t ld, int64_t pos0, float freq_base, void* stream) { - const float theta_scale = powf(freq_base, -2.0f / 64.0f); - rope_kernel<<<(unsigned) (T * heads), 32, 0, (cudaStream_t) stream>>>(x, heads, dim, ld, pos0, theta_scale, strata::kernels::mrope_table()); +void rope(float* x, int64_t T, int64_t heads, int64_t dim, int64_t ld, int64_t pos0, + const strata::kernels::RopeScaling& scaling, void* stream) { + const double fs = scaling.freq_scale(); + if (!(fs > 0.0) || scaling.freq_base <= 1.0) { + std::fprintf(stderr, "prefill rope: invalid scaling (freq_base %.6g, freq_scale %.6g)\n", + scaling.freq_base, fs); + std::exit(1); + } + const float theta_scale = powf((float) scaling.freq_base, -2.0f / 64.0f); + double corr[2]; + scaling.corr_dims(64, corr); + rope_kernel<<<(unsigned) (T * heads), 32, 0, (cudaStream_t) stream>>>( + x, heads, dim, ld, pos0, theta_scale, (float) fs, (float) corr[0], (float) corr[1], + (float) scaling.ext_factor, (float) scaling.attn_factor, strata::kernels::mrope_table()); check("rope"); } void split_q(const float* q_full, float* q, int64_t T, void* stream) { diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index bdfd9e7a63..9d900d1e55 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -1304,7 +1304,7 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e if (!bf16_proj(m.gemm, wik, m.mixed_bf, m.idx_raw, T, v.name("indexer.k_proj.weight"), err)) return false; if (!bf16_proj(m.gemm, wiq, m.mixed_bf, m.q_idx, T, v.name("indexer.q_proj.weight"), err)) return false; rms_rows(m.Kc, (const float*) wkn->data, T * 2, 256, 256, EPS, m.cs); - rope(m.Kc, T, 2, 256, 512, p0, (float) strata::kernels::qsa_freq_base(), m.cs); + rope(m.Kc, T, 2, 256, 512, p0, strata::kernels::rope_scaling(), m.cs); // KV streaming: this layer's cells [0, p0) come in from the host copy to the staging pool, and the // chunk's cells go to the host copy, the staging pool, and the VRAM slots of resident blocks const bool staged = st.kv_mode == 1; @@ -1334,10 +1334,10 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e } split_q(m.Qf, m.q, T, m.cs); rms_rows(m.q, (const float*) wqn->data, T * 24, 256, 256, EPS, m.cs); - rope(m.q, T, 24, 256, 6144, p0, (float) strata::kernels::qsa_freq_base(), m.cs); + rope(m.q, T, 24, 256, 6144, p0, strata::kernels::rope_scaling(), m.cs); if (st.kv_q4) strata::kernels::fwht256_inplace_cuda(m.q, T * 24, m.cs); rms_rows(m.q_idx, (const float*) wiqn->data, T * 4, 128, 128, EPS, m.cs); - rope(m.q_idx, T, 4, 128, 512, p0, (float) strata::kernels::qsa_freq_base(), m.cs); + rope(m.q_idx, T, 4, 128, 512, p0, strata::kernels::rope_scaling(), m.cs); // the indexer appends, token by token; then scores + selection for many queries at once: // a query reads completed blocks (final once completed) and `dead` for its own tail block const strata::kernels::QsaIndexerBuffers ib{st.idx_tail, st.idx_dead, st.idx_pooled, st.idx_block_pos}; @@ -1349,13 +1349,13 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e if (!per_token) { strata::kernels::native_qsa_indexer_append_batch(m.idx_raw, T, p0, 0, (const float*) wikn->data, EPS, ib, s, st.max_cells, - (float) strata::kernels::qsa_freq_base(), m.cs); + strata::kernels::rope_scaling(), m.cs); } for (int64_t t = 0; per_token && t < T; ++t) { const int32_t* step_t = m.steps_dev + t * strata::kernels::kStepCount; strata::kernels::native_qsa_indexer_append(m.idx_raw + t * 128, step_t + strata::kernels::kStepPos, 0, (const float*) wikn->data, EPS, ib, s, st.max_cells, - (float) strata::kernels::qsa_freq_base(), m.cs); + strata::kernels::rope_scaling(), m.cs); } } catch (const std::exception& e) { err = std::string("prefill indexer: ") + e.what(); return false; } pt.mark(kPfQsaSel, cs);