Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.
C++
kernels: rope scaling config and the scaled cos/sin table (none/linear/YaRN)
Jakub Luwierski304d613cd03e
diff --git a/include/strata/kernels/rope.hpp b/include/strata/kernels/rope.hppindex 59b66c885..45e54faf0 100644--- a/include/strata/kernels/rope.hpp+++ b/include/strata/kernels/rope.hpp@@ -6,10 +6,18 @@// The cos/sin table is built on the HOST in float64 (see src/kernels/cuda/rope.cu for why) and the kernel is// a pure rotation over it. The table depends on (n_rot, theta, position) and not on the token, so it is worth// caching; `build_rope_table` fills `max_pos` positions of `n_rot/2` pairs each.+//+// ROPE SCALING RIDES IN THE TABLE, NOT IN THE KERNEL. The kernels below read cos/sin values and+// cannot tell a scaled table from an unscaled one - with scaling on, the scaled angles (and YaRN's+// mscale magnitude correction, folded into the same values) simply ARE the table. That is why+// neither `rope_neox_apply` nor the indexer's pooling kernel takes any scaling argument: the config+// enters once, here, at build time (`rope_scaling.hpp`).#pragma once#include <cstdint>+#include "strata/kernels/rope_scaling.hpp"+#if defined(__CUDACC__) || defined(__HIPCC__)#define STRATA_ROPE_HD __host__ __device__#else@@ -38,6 +46,12 @@ STRATA_ROPE_HD inline void rope_neox_pair(float a, float b, float c, float s, flvoid build_rope_table(int n_rot, double theta, int max_pos, float* cos_tab, float* sin_tab);+/// The same table under the process's rope scaling (rope_scaling.hpp). For `RopeScalingType::None`+/// this IS the five-argument builder above - the parity test holds the two to be bit-identical - and+/// for linear/YaRN the scaled angles (YaRN's mscale included) replace them. The math is ggml's,+/// transcribed; see the header of `rope_scaling.hpp` for what arrives from where.+void build_rope_table(int n_rot, const RopeScaling& scaling, int max_pos, float* cos_tab, float* sin_tab);+// `x` and `out` are (rows, head_dim) and `pos` is (rows,) - one position per row, so a batch of heads at// different sequence positions is one call. `cos_tab`/`sin_tab` are (max_pos, n_rot/2). `out` may equal `x`.//diff --git a/include/strata/kernels/rope_scaling.hpp b/include/strata/kernels/rope_scaling.hppnew file mode 100644index 000000000..ebb052e22--- /dev/null+++ b/include/strata/kernels/rope_scaling.hpp@@ -0,0 +1,143 @@+// include/strata/kernels/rope_scaling.hpp - rope scaling: extending the context past the trained one.+//+// WHAT IT IS. The artifact's RoPE is trained over `orig_ctx` positions (the artifact ships no+// `rope.scaling` keys, so this is a pure runtime feature). Scaling re-uses positions past that by+// rescaling the rotation angles. Three types, the llama.cpp set:+//+// none freq_scale 1, no correction - today's behaviour, exactly+// linear Position Interpolation: angles shrunk by 1/factor - every position fits again, all+// frequencies compressed uniformly+// yarn YaRN: high-frequency pairs keep their trained angles (extrapolate), low-frequency+// pairs are interpolated, and the pairs in between blend - plus a magnitude correction+// `mscale` that keeps the attention temperature where training put it+//+// THE MATH IS GGML'S, TRANSCRIBED, NOT RE-DERIVED. `third_party/llama.cpp` is vendored and is the+// numerical contract (the same standing `native_rope.cu` declares): ramp, correction dims, the+// interpolation mix and the mscale formula below are line-for-line that source, with the MIT+// attribution at each helper. The one deliberate deviation is bookkeeping: ggml's device kernel+// speaks in even dim indices (`i0`) and halves them inside the ramp, while every Strata rope kernel+// speaks in PAIR indices - so `rope_yarn_ramp` here takes the pair index and compares it against+// `corr_dims` directly. Same numbers, one less division per call site.+//+// HOW IT REACHES THE ROPE. Two forms, one config:+//+// - the TABLE path (the default decode path, the indexer's pooled key) never changes its kernels:+// scaling is baked into the cos/sin contents by `build_rope_table`, which the parity test checks+// bit-exactly against a float64 reference;+// - the ANALYTIC paths (`--native-rope`, the native indexer, prefill) get the resolved constants+// as kernel arguments.+//+// **PROCESS CONSTANTS, SET ONCE BEFORE CAPTURE.** A CUDA graph bakes kernel ARGUMENTS at capture+// time, so the scaling must be fixed before `session_init` captures the layers - which is exactly+// the constraint the per-token values already respect by living in device memory (`st.pos_dev`).+// `rope_scaling_set()` is called once from the engine's startup, after CLI and GGUF defaults meet,+// before any graph exists. There is deliberately no way to change it mid-process: the K already in+// the cache is stored POST-RoPE, so a mid-run change would mix two scalings in one cache.+#pragma once++#include <cmath>++#if defined(__CUDACC__) || defined(__HIPCC__)+#define STRATA_ROPE_SCALING_HD __host__ __device__+#else+#define STRATA_ROPE_SCALING_HD+#endif++namespace strata::kernels {++enum class RopeScalingType { None, Linear, YaRN };++/// The one rope configuration, as the CLI flag family and the (future) GGUF rope keys resolve to.+///+/// Default-constructed this is EXACTLY today's engine: freq_scale 1, mscale 1, no correction. That+/// identity is a regression gate, not a coincidence - the parity test compares the default's table+/// against the pre-scaling builder bit for bit.+struct RopeScaling {+ RopeScalingType type = RopeScalingType::None;+ double freq_base = 1e7; ///< `rope.freq_base` (the value pinned by `qsa_freq_base()`)+ double factor = 1.0; ///< `--rope-scale`: how far past the trained context the run goes+ double freq_scale_in = 0; ///< `--rope-freq-scale`: the raw ggml knob; 0 = 1/factor+ double orig_ctx = 262144; ///< `--yarn-orig-ctx`: the context the model was trained over+ double ext_factor = 0; ///< `--yarn-ext-factor`: correction depth; 0 = off, 1 = full YaRN+ double attn_factor = 1.0; ///< `--yarn-attn-factor`: extra magnitude scale (ggml's attn_factor)+ double beta_fast = 32.0; ///< `--yarn-beta-fast`+ double beta_slow = 1.0; ///< `--yarn-beta-slow`++ /// The angle shrink. ggml's `freq_scale`: 1 means "the trained angles", 1/factor squeezes+ /// `factor` positions into the trained range.+ double freq_scale() const {+ if (type == RopeScalingType::None) return 1.0;+ return freq_scale_in > 0 ? freq_scale_in : 1.0 / factor;+ }++ /// The magnitude correction. ggml's `rope_yarn` multiplies cos and sin by this; the log term+ /// rides on `ext_factor != 0` (not on the type), exactly as that source has it. With the+ /// default knobs YaRN factor F gives `1 + 0.1*ln(F)` - YaRN's temperature correction.+ double mscale() const {+ if (ext_factor == 0) return attn_factor;+ return attn_factor * (1.0 + 0.1 * std::log(1.0 / freq_scale()));+ }++ /// The correction window, in PAIR indices: below `out[0]` pairs extrapolate (keep the trained+ /// angles), above `out[1]` they interpolate, in between they blend. Transcribed from ggml's+ /// `ggml_rope_yarn_corr_dims` (see the derivation comment at `rope_yarn_corr_dim` below).+ void corr_dims(int n_rot, double out[2]) const {+ const double start = std::floor(rope_yarn_corr_dim(n_rot, orig_ctx, beta_fast, freq_base));+ const double end = std::ceil(rope_yarn_corr_dim(n_rot, orig_ctx, beta_slow, freq_base));+ out[0] = start < 0 ? 0 : start;+ out[1] = end > (double) (n_rot - 1) ? (double) (n_rot - 1) : end;+ }++private:+ /// ggml/src/ggml.c: "Apparently solving `n_rot = 2pi * x * base^((2 * max_pos_emb) / n_dims)`+ /// for x, we get `corr_dim(n_rot) = n_dims * log(max_pos_emb / (n_rot * 2pi)) / (2 * log(base))`".+ /// float64 rather than ggml's float32: the table path computes in float64 and is held to a+ /// bit-exact float64 reference, so its inputs are float64 too.+ static double rope_yarn_corr_dim(int n_dims, double n_ctx_orig, double n_rot, double base) {+ return (double) n_dims * std::log(n_ctx_orig / (n_rot * 2.0 * 3.14159265358979323846)) /+ (2.0 * std::log(base));+ }+};++/// The ramp between extrapolation (1) and interpolation (0).+///+/// ggml/src/ggml-cuda/rope.cu `rope_yarn_ramp`: `1 - clamp(y, 0, 1)` with+/// `y = (i0 / 2 - low) / max(0.001, high - low)`. ggml passes the even dim index `i0`; this takes+/// the pair index (ggml's `i0/2`) so Strata's pair-indexed kernels don't re-derive the mapping. The+/// 0.001 floor on the denominator is ggml's, kept verbatim: `corr_dims` can produce low == high.+STRATA_ROPE_SCALING_HD inline float rope_yarn_ramp(float low, float high, int pair) {+ const float y = ((float) pair - low) / (high - low > 0.001f ? high - low : 0.001f);+ const float clamped = y < 0.0f ? 0.0f : (y > 1.0f ? 1.0f : y);+ return 1.0f - clamped;+}++/// The scaled angle for one pair, float32, the ANALYTIC paths' contract (pinned ggml arithmetic).+///+/// Takes `theta_extrap` - the position times that pair's trained `inv_freq` - and returns the angle+/// to take cos/sin of, with ggml's mscale already folded in. `mscale_in` must be `attn_factor`+/// (ggml's kernels receive the raw knob and apply the log term here, where it is per-pair constant;+/// this helper keeps that shape so the native path reads against ggml line by line).+STRATA_ROPE_SCALING_HD inline void rope_scaled_angle(float theta_extrap, float freq_scale, float corr_low,+ float corr_high, float ext_factor, float mscale_in,+ int pair, float& cos_out, float& sin_out) {+ // The interpolation, always applied; the correction mixed in on top (ggml-cuda/rope.cu rope_yarn).+ float theta = freq_scale * theta_extrap;+ float mscale = mscale_in;+ if (ext_factor != 0.0f) {+ const float ramp_mix = rope_yarn_ramp(corr_low, corr_high, pair) * ext_factor;+ theta = theta * (1.0f - ramp_mix) + theta_extrap * ramp_mix;+ // "Get n-d magnitude scaling corrected for interpolation" - the log term only when correcting.+ mscale *= 1.0f + 0.1f * logf(1.0f / freq_scale);+ }+ cos_out = cosf(theta) * mscale;+ sin_out = sinf(theta) * mscale;+}++/// The process's one rope configuration. Set it ONCE at startup, after the CLI and the model file+/// have agreed on the values and BEFORE `session_init` (which builds the rope table and captures the+/// graphs); read it at table build time and when launching the analytic kernels. Plain storage, no+/// atomics: one writer on the startup thread, every reader after it.+void rope_scaling_set(const RopeScaling& scaling);+const RopeScaling& rope_scaling();++} // namespace strata::kernelsdiff --git a/src/kernels/cuda/rope.cu b/src/kernels/cuda/rope.cuindex 2bb1735a8..807545eb8 100644--- a/src/kernels/cuda/rope.cu+++ b/src/kernels/cuda/rope.cu@@ -20,6 +20,11 @@// Building the table once on the host and passing it in makes the TABLE exactly the reference's values and// leaves the kernel a pure rotation, so each half can be checked tightly instead of both halves sharing one// loose tolerance. The engine wants a cached table anyway: it is per (n_rot, theta, position), not per token.+//+// THE SCALED TABLE IS THE SAME IDEA WITH MORE MATH IN THE HOST LOOP. Linear rescales the angle by+// `freq_scale`; YaRN blends extrapolation and interpolation along the pairs (ggml's `rope_yarn`) and folds+// the mscale magnitude correction into the same cos/sin values. All of it float64, in the reference's+// order, so `rope_parity` can hold every variant to a bit-exact float64 transcription of the same spec.#include "strata/kernels/rope.hpp"#include "strata/kernels/mrope.hpp"@@ -31,6 +36,15 @@namespace strata::kernels {+namespace {+// The process's rope config (rope_scaling.hpp). One writer - the engine's startup thread, before+// session_init builds any table or captures any graph - and readers after it.+RopeScaling g_rope_scaling;+} // namespace++void rope_scaling_set(const RopeScaling& scaling) { g_rope_scaling = scaling; }+const RopeScaling& rope_scaling() { return g_rope_scaling; }+void build_rope_table(int n_rot, double theta, int max_pos, float* cos_tab, float* sin_tab) {const int half = n_rot / 2;for (int p = 0; p < max_pos; ++p) {@@ -44,6 +58,33 @@ void build_rope_table(int n_rot, double theta, int max_pos, float* cos_tab, floa}}+void build_rope_table(int n_rot, const RopeScaling& sc, int max_pos, float* cos_tab, float* sin_tab) {+ if (sc.type == RopeScalingType::None) {+ build_rope_table(n_rot, sc.freq_base, max_pos, cos_tab, sin_tab); // the original loop, verbatim+ return;+ }+ const int half = n_rot / 2;+ const double fs = sc.freq_scale();+ const double ms = sc.mscale();+ double cd[2];+ sc.corr_dims(n_rot, cd);+ const bool correct = sc.ext_factor != 0; // ggml: the correction rides on ext_factor, not the type+ for (int p = 0; p < max_pos; ++p) {+ for (int i = 0; i < half; ++i) {+ const double inv = std::pow(sc.freq_base, -2.0 * (double) i / (double) n_rot);+ const double extrap = (double) p * inv; // the trained angle, ggml's theta_extrap+ const double interp = fs * extrap; // ggml's theta_interp+ double ang = interp;+ if (correct) {+ const double ramp = (double) rope_yarn_ramp((float) cd[0], (float) cd[1], i) * sc.ext_factor;+ ang = interp * (1.0 - ramp) + extrap * ramp;+ }+ cos_tab[(size_t) p * half + i] = (float) (std::cos(ang) * ms);+ sin_tab[(size_t) p * half + i] = (float) (std::sin(ang) * ms);+ }+ }+}+namespace {// ONE THREAD PER ROW, not per (row, pair). The first version had one thread per pair and did the tail copydiff --git a/src/kernels/rope_parity.cpp b/src/kernels/rope_parity.cppindex 8460b4871..39ba116a5 100644--- a/src/kernels/rope_parity.cpp+++ b/src/kernels/rope_parity.cpp@@ -12,7 +12,20 @@// A single end-to-end comparison would have had to carry one loose tolerance for both, and the interesting// failure - the NEOX pairing being wrong - is a PERMUTATION that a loose tolerance over all 256 dims would// happily accept.+//+// Check 4 extends the same discipline to the SCALED tables (rope scaling: none/linear/YaRN). The rotation+// kernel cannot see scaling - it lives in the table contents - so each variant's TABLE is held to a float64+// transcription of ggml's `rope_yarn` spec (the ramp helper is shared, the `rope_neox_pair` convention), and+// the two properties a tolerance could never fake get their own structural checks: at position 0 every pair's+// angle is 0, so YaRN's mscale stands naked in cos_tab[0], and at a far position the first pair must match+// EXTRAPOLATION while the last matches INTERPOLATION. An observability assertion closes it: if the scaled+// and unscaled tables were indistinguishable, every green number above would be vacuous.+//+// Check 5 holds the TWO PATHS together: the table path's float64 host trig and the native path's float32+// fast-math device trig must answer to the same `RopeScaling`, yarn and none alike, so one cache never+// mixes two rotations.#include "strata/kernels/rope.hpp"+#include "strata/kernels/native_rope.hpp"#include <cuda_runtime.h>@@ -164,6 +177,264 @@ int main(int argc, char** argv) {if (!(neox_moved && !adjacent_moved)) ++bad;}+ // ---- 4. THE SCALED TABLES (rope_scaling.hpp). Scaling lives in the table contents, so each variant is+ // a table check: a float64 transcription of the ggml spec, bit-exact after the float32 cast, plus the+ // structural and observability checks the tolerances cannot cover.+ {+ // 4a. type None IS the five-argument builder above - bit for bit.+ std::vector<float> nc((size_t) max_pos * half), ns((size_t) max_pos * half);+ strata::kernels::RopeScaling none;+ none.freq_base = theta;+ strata::kernels::build_rope_table(n_rot, none, max_pos, nc.data(), ns.data());+ const long long none_bad =+ (long long) (std::memcmp(nc.data(), hcos.data(), nc.size() * 4) != 0) ++ (long long) (std::memcmp(ns.data(), hsin.data(), ns.size() * 4) != 0);+ std::printf(" scaled table, None vs unscaled builder %s\n", none_bad ? "*** WRONG ***" : "bit-identical");+ bad += (int) none_bad;++ // 4b. LINEAR, factor 4: `ang = p * inv / 4` in float64. The factor is a power of two on purpose -+ // dividing by it is exact, so no multiplication-order rounding can sneak between spec and builder.+ strata::kernels::RopeScaling lin;+ lin.type = strata::kernels::RopeScalingType::Linear;+ lin.freq_base = theta;+ lin.factor = 4.0;+ std::vector<float> lc((size_t) max_pos * half), ls((size_t) max_pos * half);+ strata::kernels::build_rope_table(n_rot, lin, max_pos, lc.data(), ls.data());+ long long lin_bad = 0;+ for (int p = 0; p < max_pos; ++p) {+ for (int i = 0; i < half; ++i) {+ const double inv = std::pow(theta, -2.0 * (double) i / (double) n_rot);+ const double ang = (double) p * inv / 4.0;+ const float rc = (float) std::cos(ang), rs = (float) std::sin(ang);+ if (std::memcmp(&rc, &lc[(size_t) p * half + i], 4) != 0) ++lin_bad;+ if (std::memcmp(&rs, &ls[(size_t) p * half + i], 4) != 0) ++lin_bad;+ }+ }+ std::printf(" scaled table, linear factor 4 %s (%lld of %d entries differ)\n",+ lin_bad ? "*** WRONG ***" : "bit-exact", lin_bad, max_pos * half * 2);+ bad += (int) lin_bad;++ // 4c. THE INTERPOLATION CLAIM ITSELF: linear(4) at position p is `none` at p/4 - the same table row,+ // bit for bit, at every position divisible by the factor.+ std::vector<float> wc((size_t) 4 * max_pos * half), ws((size_t) 4 * max_pos * half);+ strata::kernels::build_rope_table(n_rot, lin, 4 * max_pos, wc.data(), ws.data());+ long long equiv_bad = 0;+ for (int p = 0; p < 4 * max_pos; p += 4) {+ for (int i = 0; i < half; ++i) {+ if (std::memcmp(&wc[(size_t) p * half + i], &hcos[(size_t) (p / 4) * half + i], 4) != 0) ++equiv_bad;+ if (std::memcmp(&ws[(size_t) p * half + i], &hsin[(size_t) (p / 4) * half + i], 4) != 0) ++equiv_bad;+ }+ }+ std::printf(" linear(4) @ p == none @ p/4 %s (%lld of %d rows differ)\n",+ equiv_bad ? "*** WRONG ***" : "bit-identical", equiv_bad, max_pos);+ bad += (int) equiv_bad;++ // 4d. YARN vs a float64 transcription of ggml's rope_yarn (factor 4, the default correction knobs).+ // The ramp helper is shared with the builder (the rope_neox_pair convention: one definition, not two+ // transcriptions of it); the interpolation mix and the mscale formula are written here from the ggml+ // source lines, which is the spec being tested.+ strata::kernels::RopeScaling yarn;+ yarn.type = strata::kernels::RopeScalingType::YaRN;+ yarn.freq_base = theta;+ yarn.factor = 4.0;+ yarn.ext_factor = 1.0;+ std::vector<float> yc((size_t) max_pos * half), ys((size_t) max_pos * half);+ strata::kernels::build_rope_table(n_rot, yarn, max_pos, yc.data(), ys.data());+ const double fs = yarn.freq_scale(); // 0.25+ const double ms = yarn.mscale(); // attn_factor * (1 + 0.1*ln(4))+ double cd[2];+ yarn.corr_dims(n_rot, cd);+ long long yarn_bad = 0;+ for (int p = 0; p < max_pos; ++p) {+ for (int i = 0; i < half; ++i) {+ const double inv = std::pow(theta, -2.0 * (double) i / (double) n_rot);+ const double extrap = (double) p * inv;+ const double interp = fs * extrap;+ const double ramp = (double) strata::kernels::rope_yarn_ramp((float) cd[0], (float) cd[1], i) *+ yarn.ext_factor;+ const double ang = interp * (1.0 - ramp) + extrap * ramp;+ const float rc = (float) (std::cos(ang) * ms), rs = (float) (std::sin(ang) * ms);+ if (std::memcmp(&rc, &yc[(size_t) p * half + i], 4) != 0) ++yarn_bad;+ if (std::memcmp(&rs, &ys[(size_t) p * half + i], 4) != 0) ++yarn_bad;+ }+ }+ std::printf(" scaled table, yarn factor 4 %s (%lld of %d entries differ)\n",+ yarn_bad ? "*** WRONG ***" : "bit-exact", yarn_bad, max_pos * half * 2);+ bad += (int) yarn_bad;++ // 4e. THE STRUCTURE a tolerance cannot fake. At position 0 every pair's angle is 0, so YaRN's whole+ // magnitude correction stands naked: cos_tab[0] == mscale. At the far end of the table the first+ // pair (the highest trained frequency) must match EXTRAPOLATION and the last INTERPOLATION. The two+ // halves need different observables: at the first pair cos separates the hypotheses outright, but at+ // the last they differ by ~4 microradians here, invisible to cos near 1 - sin sees it, because near+ // zero sin IS the angle. That asymmetry is the YaRN design: interpolation happens where angles are+ // small. Both hypotheses go through the same mix formula the builder uses, so the bit comparison is+ // spec against spec, not shortcut against implementation.+ {+ const float msv = (float) ms;+ const bool zero_ok = std::memcmp(&msv, &yc[0], 4) == 0 && ys[0] == 0.0f;+ const int far = max_pos - 1;+ const double inv_f = 1.0; // pair 0: theta ** 0+ const double extrap_f = (double) far * inv_f, interp_f = fs * extrap_f;+ const double inv_l = std::pow(theta, -2.0 * (double) (half - 1) / (double) n_rot);+ const double extrap_l = (double) far * inv_l, interp_l = fs * extrap_l;+ const float ef = (float) (std::cos(interp_f * (1.0 - 1.0) + extrap_f * 1.0) * ms);+ const float itf = (float) (std::cos(interp_f * (1.0 - 0.0) + extrap_f * 0.0) * ms);+ const float sl_e = (float) (std::sin(interp_l * (1.0 - 1.0) + extrap_l * 1.0) * ms);+ const float sl_i = (float) (std::sin(interp_l * (1.0 - 0.0) + extrap_l * 0.0) * ms);+ const float got_f = yc[(size_t) far * half], got_l = ys[(size_t) far * half + (half - 1)];+ const bool first_extrapolates = std::memcmp(&got_f, &ef, 4) == 0;+ const bool last_interpolates = std::memcmp(&got_l, &sl_i, 4) == 0;+ const bool distinguishable = std::fabs((double) ef - (double) itf) > 1e-3 &&+ std::fabs((double) sl_e - (double) sl_i) > 1e-8;+ std::printf(" yarn structure: cos_tab[0]==mscale %.4f, first pair extrapolates, last interpolates "+ "%s\n", (double) msv,+ zero_ok && first_extrapolates && last_interpolates && distinguishable+ ? "confirmed"+ : "*** WRONG ***");+ if (!(zero_ok && first_extrapolates && last_interpolates && distinguishable)) ++bad;+ }++ // 4f. THE OBSERVABILITY assertion: the fixtures must SEE scaling. If the builder ignored its config,+ // linear(2) would equal `none` everywhere and 4b-4e would be green on a broken builder.+ {+ strata::kernels::RopeScaling lin2;+ lin2.type = strata::kernels::RopeScalingType::Linear;+ lin2.freq_base = theta;+ lin2.factor = 2.0;+ std::vector<float> l2c((size_t) 101 * half), l2s((size_t) 101 * half);+ strata::kernels::build_rope_table(n_rot, lin2, 101, l2c.data(), l2s.data());+ const float c_none = (float) std::cos(100.0); // pair 0, position 100, unscaled: ang = 100+ const float c_lin = l2c[(size_t) 100 * half]; // pair 0, position 100, linear(2): ang = 50+ const bool sees = std::fabs((double) c_none - (double) c_lin) > 1e-3;+ std::printf(" observability: none vs linear(2) at position 100 %s (|%.4f - %.4f|)\n",+ sees ? "visible" : "*** VACUUM ***", (double) c_none, (double) c_lin);+ if (!sees) ++bad;+ }++ // 4g. THE ROTATION under a scaled table. The kernel is table-agnostic and must not know or care:+ // the host reference is the same rope_neox_pair walk as check 2, over the YaRN table.+ std::vector<float> ref2(x.size());+ for (int r = 0; r < rows; ++r) {+ const float* xr = &x[(size_t) r * head_dim];+ float* orow = &ref2[(size_t) r * head_dim];+ for (int d = 0; d < head_dim; ++d) orow[d] = xr[d];+ for (int i = 0; i < half; ++i) {+ float c = yc[(size_t) pos[(size_t) r] * half + i], s = ys[(size_t) pos[(size_t) r] * half + i];+ strata::kernels::rope_neox_pair(xr[i], xr[half + i], c, s, orow[i], orow[half + i]);+ }+ }+ check(cudaMemcpy(d_x, x.data(), x.size() * sizeof(float), cudaMemcpyHostToDevice), "copy x");+ check(cudaMemcpy(d_cos, yc.data(), yc.size() * sizeof(float), cudaMemcpyHostToDevice), "copy ycos");+ check(cudaMemcpy(d_sin, ys.data(), ys.size() * sizeof(float), cudaMemcpyHostToDevice), "copy ysin");+ check(cudaMemcpy(d_pos, pos.data(), pos.size() * sizeof(int), cudaMemcpyHostToDevice), "copy pos");+ strata::kernels::rope_neox_apply(d_x, d_out, rows, head_dim, n_rot, d_cos, d_sin, d_pos, nullptr);+ std::vector<float> got2(ref2.size());+ check(cudaMemcpy(got2.data(), d_out, got2.size() * sizeof(float), cudaMemcpyDeviceToHost), "back");+ long long rot2_bad = 0;+ double worst2 = 0.0;+ for (size_t i = 0; i < ref2.size(); ++i) {+ const double a = ref2[i], b = got2[i];+ const double rel = std::fabs(a - b) / row_scale[i / (size_t) head_dim];+ worst2 = std::max(worst2, rel);+ if (!(rel <= 1e-6)) ++rot2_bad;+ }+ std::printf(" rope rotation over the yarn table %s (%lld of %zu over 1e-6, worst rel %.3e)\n",+ rot2_bad ? "*** WRONG ***" : "agrees", rot2_bad, ref2.size(), worst2);+ bad += (int) rot2_bad;+ }++ // ---- 5. THE TWO PATHS MUST AGREE. The table path (the default) computes cos/sin on the host in float64;+ // the native path (`--native-rope`) computes the same angles on device in float32 under `--use_fast_math`.+ // They answer to ONE config - `RopeScaling` - and a disagreement between them would put differently-rotated+ // K into the cache depending on which path ran. The tolerance is NOT the 1e-6 of checks 2/4g: the device+ // side takes fast-math trig at angles up to ~2048 rad, where the fp32 range reduction alone is worth ~1e-4,+ // so the bar is the row-magnitude-relative 3e-3 and the test keeps the positions where that holds. (The+ // engine's default is the table path precisely because float64 host trig has no such floor.)+ {+ const int npos = 2048;+ strata::kernels::RopeScaling yarn;+ yarn.type = strata::kernels::RopeScalingType::YaRN;+ yarn.factor = 2.0;+ yarn.ext_factor = 1.0;+ std::vector<float> sc((size_t) npos * half), ss((size_t) npos * half);+ strata::kernels::build_rope_table(n_rot, yarn, npos, sc.data(), ss.data());+ std::mt19937 rng2(23);+ std::normal_distribution<float> gauss2(0.0f, 1.0f);+ const int nrows = 24 * 16; // 16 positions spread over the table's range+ std::vector<float> x2((size_t) nrows * head_dim);+ for (auto& v : x2) v = gauss2(rng2);+ std::vector<int> pos2((size_t) nrows);+ for (int r = 0; r < nrows; ++r) pos2[(size_t) r] = (r * 127) % npos;++ float *d_x2 = nullptr, *d_t2 = nullptr, *d_n2 = nullptr, *d_c2 = nullptr, *d_s2 = nullptr;+ int* d_p2 = nullptr;+ check(cudaMalloc(&d_x2, x2.size() * sizeof(float)), "malloc x2");+ check(cudaMalloc(&d_t2, x2.size() * sizeof(float)), "malloc t2");+ check(cudaMalloc(&d_n2, x2.size() * sizeof(float)), "malloc n2");+ check(cudaMalloc(&d_c2, sc.size() * sizeof(float)), "malloc c2");+ check(cudaMalloc(&d_s2, ss.size() * sizeof(float)), "malloc s2");+ check(cudaMalloc(&d_p2, pos2.size() * sizeof(int)), "malloc p2");+ check(cudaMemcpy(d_x2, x2.data(), x2.size() * sizeof(float), cudaMemcpyHostToDevice), "copy x2");+ check(cudaMemcpy(d_c2, sc.data(), sc.size() * sizeof(float), cudaMemcpyHostToDevice), "copy c2");+ check(cudaMemcpy(d_s2, ss.data(), ss.size() * sizeof(float), cudaMemcpyHostToDevice), "copy s2");+ check(cudaMemcpy(d_p2, pos2.data(), pos2.size() * sizeof(int), cudaMemcpyHostToDevice), "copy p2");+ // The native path demands an explicit stream - a null one is refused by validation, not defaulted.+ cudaStream_t cs5 = nullptr;+ check(cudaStreamCreate(&cs5), "stream5");+ strata::kernels::rope_neox_apply(d_x2, d_t2, nrows, head_dim, n_rot, d_c2, d_s2, d_p2, nullptr);+ strata::kernels::native_rope_apply(d_x2, d_n2, nrows, head_dim, n_rot, yarn, d_p2, cs5);+ check(cudaStreamSynchronize(cs5), "sync5");+ std::vector<float> got_t(x2.size()), got_n(x2.size());+ check(cudaMemcpy(got_t.data(), d_t2, got_t.size() * sizeof(float), cudaMemcpyDeviceToHost), "back t2");+ check(cudaMemcpy(got_n.data(), d_n2, got_n.size() * sizeof(float), cudaMemcpyDeviceToHost), "back n2");+ long long agree_bad = 0;+ double worst = 0.0;+ for (int r = 0; r < nrows; ++r) {+ double m = 0;+ for (int d = 0; d < head_dim; ++d) m = std::max(m, (double) std::fabs(x2[(size_t) r * head_dim + d]));+ const double scale = m > 1e-30 ? m : 1e-30;+ for (int d = 0; d < head_dim; ++d) {+ const double rel = std::fabs((double) got_t[(size_t) r * head_dim + d] -+ (double) got_n[(size_t) r * head_dim + d]) / scale;+ worst = std::max(worst, rel);+ if (!(rel <= 3e-3)) ++agree_bad;+ }+ }+ std::printf(" native path vs table path, yarn factor 2 %s (%lld of %d over 3e-3, worst rel %.3e)\n",+ agree_bad ? "*** WRONG ***" : "agrees", agree_bad, nrows * head_dim, worst);+ bad += (int) agree_bad;++ // and the None config: the native path against the UNSCALED table - the identity this feature must+ // not disturb.+ strata::kernels::RopeScaling none5; // all defaults: type None, freq_scale 1, mscale 1+ strata::kernels::native_rope_apply(d_x2, d_n2, nrows, head_dim, n_rot, none5, d_p2, cs5);+ check(cudaStreamSynchronize(cs5), "sync5b");+ check(cudaMemcpy(got_n.data(), d_n2, got_n.size() * sizeof(float), cudaMemcpyDeviceToHost), "back n2b");+ std::vector<float> nc5((size_t) npos * half), ns5((size_t) npos * half);+ strata::kernels::build_rope_table(n_rot, none5, npos, nc5.data(), ns5.data());+ check(cudaMemcpy(d_c2, nc5.data(), nc5.size() * sizeof(float), cudaMemcpyHostToDevice), "copy c2b");+ check(cudaMemcpy(d_s2, ns5.data(), ns5.size() * sizeof(float), cudaMemcpyHostToDevice), "copy s2b");+ strata::kernels::rope_neox_apply(d_x2, d_t2, nrows, head_dim, n_rot, d_c2, d_s2, d_p2, nullptr);+ check(cudaMemcpy(got_t.data(), d_t2, got_t.size() * sizeof(float), cudaMemcpyDeviceToHost), "back t2b");+ long long none_bad5 = 0;+ double worst5 = 0.0;+ for (int r = 0; r < nrows; ++r) {+ double m = 0;+ for (int d = 0; d < head_dim; ++d) m = std::max(m, (double) std::fabs(x2[(size_t) r * head_dim + d]));+ const double scale = m > 1e-30 ? m : 1e-30;+ for (int d = 0; d < head_dim; ++d) {+ const double rel = std::fabs((double) got_t[(size_t) r * head_dim + d] -+ (double) got_n[(size_t) r * head_dim + d]) / scale;+ worst5 = std::max(worst5, rel);+ if (!(rel <= 3e-3)) ++none_bad5;+ }+ }+ std::printf(" native path vs table path, none %s (%lld of %d over 3e-3, worst rel %.3e)\n",+ none_bad5 ? "*** WRONG ***" : "agrees", none_bad5, nrows * head_dim, worst5);+ bad += (int) none_bad5;+ }+std::printf("\nrope: %d failures\n", bad);if (bad) return 1;if (selftest) std::printf("rope_parity OK\n");