From 304d613cd03edd6ef4d0f7f62a1bf4d290863107 Mon Sep 17 00:00:00 2001 From: Jakub Luwierski Date: Mon, 28 Sep 2026 20:55:42 +0200 Subject: [PATCH 01/18] kernels: rope scaling config and the scaled cos/sin table (none/linear/YaRN) The artifact pins theta 1e7 with no rope.scaling keys, so the engine had exactly one rope: inv[i] = theta**(-2i/n_rot), no freq_scale, no correction. Contexts past the trained 262,144 had no coherent path. rope_scaling.hpp adds the one process config - none | linear | YaRN, llama.cpp's types - and build_rope_table grows an overload that folds the whole scaled angle (ggml's rope_yarn: interpolation, the corr_dims ramp along the pairs, and the mscale magnitude correction) into the float64 host table. The rotation kernels cannot tell a scaled table from an unscaled one, so nothing downstream changes: for the default decode path and the indexer's pooled key, scaling IS the table. The math is transcribed from the vendored ggml (ggml.c corr_dims, ggml-cuda/ rope.cu rope_yarn/ramp, MIT headers kept), not re-derived; the one deliberate deviation is bookkeeping - the ramp takes the PAIR index ggml's i0/2 would produce, because every Strata rope kernel speaks in pairs. For type None the new builder calls the original loop verbatim, and the parity test holds it bit-identical; linear(4) is checked bit-exact against a float64 reference and equal row-for-row to none at p/4; YaRN against a float64 transcription of the ggml spec, plus the structural checks a tolerance cannot fake: cos_tab[0] == mscale (position 0 is angle 0 for every pair), first pair extrapolates / last interpolates at a far position (cos for the first, sin for the last - near zero sin IS the angle, which is where interpolation happens), and an observability assertion that the fixtures see scaling at all. --- include/strata/kernels/rope.hpp | 14 ++ include/strata/kernels/rope_scaling.hpp | 143 +++++++++++++ src/kernels/cuda/rope.cu | 41 ++++ src/kernels/rope_parity.cpp | 271 ++++++++++++++++++++++++ 4 files changed, 469 insertions(+) create mode 100644 include/strata/kernels/rope_scaling.hpp diff --git a/include/strata/kernels/rope.hpp b/include/strata/kernels/rope.hpp index 59b66c88..45e54faf 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 +#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, fl void 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.hpp new file mode 100644 index 00000000..ebb052e2 --- /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 + +#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::kernels diff --git a/src/kernels/cuda/rope.cu b/src/kernels/cuda/rope.cu index 2bb1735a..807545eb 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 copy diff --git a/src/kernels/rope_parity.cpp b/src/kernels/rope_parity.cpp index 8460b487..39ba116a 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 @@ -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 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 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 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 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 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 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 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 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 gauss2(0.0f, 1.0f); + const int nrows = 24 * 16; // 16 positions spread over the table's range + std::vector x2((size_t) nrows * head_dim); + for (auto& v : x2) v = gauss2(rng2); + std::vector 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 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 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"); From 0011637753edf8eda42c586771603aeed5f5a94b Mon Sep 17 00:00:00 2001 From: Jakub Luwierski Date: Mon, 28 Sep 2026 20:56:03 +0200 Subject: [PATCH 02/18] rope: thread scaling through the native, indexer and prefill rotation sites The table path got scaling for free (it lives in the table contents); the three ANALYTIC paths computed the angle in-kernel and so need the config explicitly. Each wrapper now takes the RopeScaling and passes the resolved constants - freq_scale, the corr_dims pair, ext_factor, attn_factor - as kernel arguments. They are process constants set before session_init, so baking them at CUDA-graph capture is correct by the same argument as every other kernel argument: only per-token values must ride device memory, and positions still do (st.pos_dev). The shared float32 arithmetic is rope_scaled_angle (rope_scaling.hpp), a line-for-line rope_yarn: one definition for native_rope, the native indexer's pooled-key rotation and prefill's rope, instead of three transcriptions that could drift. The spare indexer key keeps its zero angle; under YaRN the mscale rides in through cos(0) on both pooled keys and indexer queries, so top-k is unmoved. rope_parity adds the check this whole wiring answers to: native vs table on the same input, yarn and none alike - which caught the first draft passing scaling.mscale() into the helper that applies the log term itself, a double magnitude correction visible as ~7% on every rotated dim. --- include/strata/kernels/native_qsa_indexer.hpp | 8 +- include/strata/kernels/native_rope.hpp | 16 ++-- include/strata/kernels/qsa.hpp | 5 +- include/strata/prefill/kernels.hpp | 7 +- src/core/layer.cpp | 7 +- src/core/mtp.cpp | 2 +- src/core/verify.cpp | 6 +- src/kernels/cuda/native_qsa_indexer.cu | 78 ++++++++++++++----- src/kernels/cuda/native_rope.cu | 30 +++++-- src/prefill/kernels.cu | 27 +++++-- src/prefill/prefill.cpp | 10 +-- 11 files changed, 140 insertions(+), 56 deletions(-) diff --git a/include/strata/kernels/native_qsa_indexer.hpp b/include/strata/kernels/native_qsa_indexer.hpp index 560b12b5..fe66d4b0 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 24bffe61..95511b88 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 e6090abf..dc26024a 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 f4256945..3a4d1ca6 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 5c6c06ef..8ad9f41a 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 2b1d79ef..a53c60e2 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 085135a9..e461ca5e 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 8a5ecbc3..86d6ae83 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 6dd3f6b5..d40c4f6b 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 50984ec9..5e74d609 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 bdfd9e7a..9d900d1e 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); From 963679b35e4fc7f692a6f59a64ec8d6db211f3bb Mon Sep 17 00:00:00 2001 From: Jakub Luwierski Date: Mon, 28 Sep 2026 20:56:15 +0200 Subject: [PATCH 03/18] engine: --rope-scaling/--rope-scale/--yarn-* flags; rope keys as GGUF defaults Nine flags, llama.cpp's names: --rope-scaling none|linear|yarn, --rope-scale, --rope-freq-base, --rope-freq-scale, --yarn-orig-ctx, --yarn-ext-factor, --yarn-attn-factor, --yarn-beta-fast, --yarn-beta-slow. Ranges die in the validation block at second zero; the config itself resolves after the model file has had its say and before session_init builds the table or captures a graph (rope_scaling.hpp's one-writer rule). Precedence: CLI over the model file's qwen4exp.rope.* keys over the struct defaults - today's artifact ships no rope keys, so that channel is a no-op defaults path for future fine-tunes. A scaled run prints its resolved summary (type, factor, freq_scale, base, mscale, context vs trained) to stderr, which is what the bench logs quote, and warns when scaling is on with the context still inside the trained range - YaRN's magnitude correction applies everywhere, so that run is not the stock model. --- src/program/generate.cpp | 111 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 111 insertions(+) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 60700870..cb0f9d50 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -129,6 +129,19 @@ struct Options { bool native_flash_attn_short = false; // diagnostic pinned attention, context <=256 bool native_qsa_indexer = false; // pinned F16 key cache and F32 pooling bool native_qsa = false; // pinned F32 QSA norms and gate + /// THE CONTEXT EXTENSION (rope scaling, rope_scaling.hpp). These knobs resolve to ONE process config, + /// set once before `session_init` builds the rope table and the graphs capture the kernels. There is + /// deliberately no per-request form: K sits in the cache POST-RoPE, so one cache must never mix two + /// scalings. Precedence: CLI over the model file's rope keys over the struct defaults. + std::string rope_scaling = "none"; ///< --rope-scaling none|linear|yarn (llama.cpp's names) + double rope_scale = 1.0; ///< --rope-scale F: the extension factor; 1 = off + double rope_freq_base = 0; ///< --rope-freq-base N: 0 = the model's (1e7) + double rope_freq_scale = 0; ///< --rope-freq-scale F: the raw ggml knob; 0 = 1/--rope-scale + double yarn_orig_ctx = 0; ///< --yarn-orig-ctx N: 0 = the model's, else 262144 + double yarn_ext_factor = -1.0; ///< --yarn-ext-factor F: <0 = auto (1 for yarn, 0 otherwise) + double yarn_attn_factor = 1.0; ///< --yarn-attn-factor F + double yarn_beta_fast = 32.0; ///< --yarn-beta-fast F + double yarn_beta_slow = 1.0; ///< --yarn-beta-slow F bool native_rope = false; // pinned text-only CUDA rotary arithmetic bool native_ple_postops = false; // pinned PLE postprojection arithmetic bool native_router = false; // pinned fused 512-expert top-10 router @@ -360,6 +373,15 @@ void usage() { " --expert-cache-cpu-order experimental GPU expert reduction matching CPU order\n" " --max-new N tokens to generate (default 16)\n" " --max-context N KV/state capacity (default 4096)\n" + " --rope-scaling T extend the context past the trained one: none (default), linear\n" + " (position interpolation) or yarn - llama.cpp's types and names.\n" + " Fixed at startup: K in the cache is post-RoPE, so one run one scaling\n" + " --rope-scale F the extension factor for linear/yarn (default 1 = off)\n" + " --rope-freq-base N the raw ggml knobs: the frequency base (0 = the model's 1e7) and\n" + " --rope-freq-scale F the angle shrink (0 = 1/--rope-scale)\n" + " --yarn-orig-ctx N the trained context the correction targets (0 = 262144)\n" + " --yarn-ext-factor F --yarn-attn-factor F --yarn-beta-fast F --yarn-beta-slow F\n" + " YaRN's knobs; defaults: -1 (auto: 1 for yarn), 1, 32, 1\n" " --greedy argmax (the default)\n" " --seed S enable sampling with this Philox seed\n" " --top-k N --top-p F --temperature F\n" @@ -930,6 +952,15 @@ int main(int argc, char** argv) { } else if (a == "--max-new") o.max_new = std::atoll(next("--max-new")); else if (a == "--max-context") o.max_context = std::atoll(next("--max-context")); + else if (a == "--rope-scaling") o.rope_scaling = next("--rope-scaling"); + else if (a == "--rope-scale") o.rope_scale = std::atof(next("--rope-scale")); + else if (a == "--rope-freq-base") o.rope_freq_base = std::atof(next("--rope-freq-base")); + else if (a == "--rope-freq-scale") o.rope_freq_scale = std::atof(next("--rope-freq-scale")); + else if (a == "--yarn-orig-ctx") o.yarn_orig_ctx = std::atof(next("--yarn-orig-ctx")); + else if (a == "--yarn-ext-factor") o.yarn_ext_factor = std::atof(next("--yarn-ext-factor")); + else if (a == "--yarn-attn-factor") o.yarn_attn_factor = std::atof(next("--yarn-attn-factor")); + else if (a == "--yarn-beta-fast") o.yarn_beta_fast = std::atof(next("--yarn-beta-fast")); + else if (a == "--yarn-beta-slow") o.yarn_beta_slow = std::atof(next("--yarn-beta-slow")); else if (a == "--greedy") o.greedy = true; else if (a == "--seed") { o.seed = (uint64_t) std::atoll(next("--seed")); o.greedy = false; } else if (a == "--top-k") o.top_k = std::atoi(next("--top-k")); @@ -1279,6 +1310,36 @@ int main(int argc, char** argv) { std::fprintf(stderr, "strata generate: positive --max-new and --max-context must fit the prompt and generation\n"); return 2; } + // THE ROPE KNOBS (rope_scaling.hpp). Anything invalid dies here, at second zero, rather than becoming a + // NaN angle inside one of the twelve QSA layers. Only the RANGES are checked - the config itself is + // resolved after the model file has had its say, right before session_init. + strata::kernels::RopeScaling rope_cfg; // type filled here; the rest at the resolution below + { + using RST = strata::kernels::RopeScalingType; + if (o.rope_scaling == "none") rope_cfg.type = RST::None; + else if (o.rope_scaling == "linear") rope_cfg.type = RST::Linear; + else if (o.rope_scaling == "yarn") rope_cfg.type = RST::YaRN; + else { + std::fprintf(stderr, "strata generate: --rope-scaling must be none, linear or yarn (got '%s')\n", + o.rope_scaling.c_str()); + return 2; + } + if (o.rope_scale < 1.0) { + std::fprintf(stderr, "strata generate: --rope-scale %g must be >= 1 (it extends the context, not shrinks it)\n", + o.rope_scale); + return 2; + } + if (o.rope_freq_base != 0 && o.rope_freq_base <= 1.0) { + std::fprintf(stderr, "strata generate: --rope-freq-base must be a base above 1 (0 = the model's)\n"); + return 2; + } + if (o.rope_freq_scale < 0 || o.yarn_orig_ctx < 0 || o.yarn_ext_factor < -1.0 || o.yarn_attn_factor <= 0 || + o.yarn_beta_fast <= 0 || o.yarn_beta_slow <= 0) { + std::fprintf(stderr, "strata generate: invalid rope scaling knob (see usage: --yarn-ext-factor <0 = auto, " + "--yarn-orig-ctx 0 = default, the rest positive)\n"); + return 2; + } + } if (!std::isfinite(o.temperature) || o.temperature < 0 || !std::isfinite(o.top_p) || o.top_p <= 0 || o.top_p > 1 || o.top_k < 0 || o.expert_cache < -1 || o.pool_workers < 0 || std::any_of(o.expert_cache_remote.begin(), o.expert_cache_remote.end(), @@ -1477,6 +1538,10 @@ int main(int argc, char** argv) { strata::kernels::ple_set_native_postops(o.native_ple_postops); strata::core::ModelGeometry g; // canonical defaults; the model file overrides the MoE shape below int64_t K = 10; + // The model file's rope keys (llama.cpp's names under the arch prefix), when it carries any - the + // artifact today ships none, so this is a no-op defaults channel for future fine-tunes. + std::string gguf_rope_type; + double gguf_rope_base = 0, gguf_rope_factor = 0, gguf_rope_orig_ctx = 0; if (!o.native_preset.empty()) { // a pruned variant (GSQ-RCO Coder) ships fewer experts than the canonical 512x10; the model file // is the authority on its own MoE shape - everything else in the geometry is unchanged @@ -1484,12 +1549,58 @@ int main(int argc, char** argv) { strata::GgufFile model_gguf(o.native_preset); if (const strata::MetaValue* v = model_gguf.get("qwen4exp.expert_count")) g.n_expert = (int64_t) v->u; if (const strata::MetaValue* v = model_gguf.get("qwen4exp.expert_used_count")) K = (int64_t) v->u; + if (const strata::MetaValue* v = model_gguf.get("qwen4exp.rope.freq_base")) gguf_rope_base = v->num(); + if (const strata::MetaValue* v = model_gguf.get("qwen4exp.rope.scaling.type")) gguf_rope_type = v->s; + if (const strata::MetaValue* v = model_gguf.get("qwen4exp.rope.scaling.factor")) gguf_rope_factor = v->num(); + if (const strata::MetaValue* v = model_gguf.get("qwen4exp.rope.scaling.original_context_length")) + gguf_rope_orig_ctx = v->num(); } catch (const std::exception& e) { std::fprintf(stderr, "strata generate: reading the model's expert shape from %s: %s\n", o.native_preset.c_str(), e.what()); return 1; } } + // THE ROPE CONFIG RESOLVES HERE - the CLI and the model file have both spoken, and `session_init` + // below builds the rope table from it and captures the kernels reading its constants (rope_scaling.hpp). + // Precedence: CLI over model file over the struct defaults. An explicit `--rope-scaling none` and the + // untouched default are the same choice: the CLI opt-out wins over the model file too. + { + using RST = strata::kernels::RopeScalingType; + if (rope_cfg.type == RST::None && !gguf_rope_type.empty()) { + if (gguf_rope_type == "linear") rope_cfg.type = RST::Linear; + else if (gguf_rope_type == "yarn") rope_cfg.type = RST::YaRN; + else if (gguf_rope_type != "none") { + std::fprintf(stderr, "strata generate: %s carries rope.scaling.type '%s' - none, linear or yarn only\n", + o.native_preset.c_str(), gguf_rope_type.c_str()); + return 2; + } + } + rope_cfg.factor = (o.rope_scale == 1.0 && gguf_rope_factor > 1.0) ? gguf_rope_factor : o.rope_scale; + if (o.rope_freq_base > 0) rope_cfg.freq_base = o.rope_freq_base; + else if (gguf_rope_base > 1.0) rope_cfg.freq_base = gguf_rope_base; + if (o.yarn_orig_ctx > 0) rope_cfg.orig_ctx = o.yarn_orig_ctx; + else if (gguf_rope_orig_ctx >= 1) rope_cfg.orig_ctx = gguf_rope_orig_ctx; + rope_cfg.freq_scale_in = o.rope_freq_scale; + rope_cfg.ext_factor = o.yarn_ext_factor >= 0 ? o.yarn_ext_factor + : (rope_cfg.type == RST::YaRN ? 1.0 : 0.0); + rope_cfg.attn_factor = o.yarn_attn_factor; + rope_cfg.beta_fast = o.yarn_beta_fast; + rope_cfg.beta_slow = o.yarn_beta_slow; + strata::kernels::rope_scaling_set(rope_cfg); + if (rope_cfg.type != RST::None) { + const char* tn = rope_cfg.type == RST::YaRN ? "yarn" : "linear"; + std::fprintf(stderr, + "strata generate: rope scaling %s, factor %.6g (freq_scale %.6g, base %.6g, mscale %.6f), " + "--max-context %lld against a trained context of %.0f\n", + tn, rope_cfg.factor, rope_cfg.freq_scale(), rope_cfg.freq_base, rope_cfg.mscale(), + (long long) o.max_context, rope_cfg.orig_ctx); + if ((double) o.max_context <= rope_cfg.orig_ctx) + std::fprintf(stderr, + "strata generate: note: the context is within the trained %.0f - the angles barely move, " + "but YaRN's magnitude correction applies everywhere\n", + rope_cfg.orig_ctx); + } + } // before session_init: every graph captured from here on has the vector's kernels where it applies std::string cvec_summary = "0"; if (!o.cvec_files.empty()) { From 9ede9d94bc544d6e25e31a15956eb58239f51de8 Mon Sep 17 00:00:00 2001 From: Jakub Luwierski Date: Mon, 28 Sep 2026 21:20:01 +0200 Subject: [PATCH 04/18] setup: --rope-scaling/--rope-scale; contexts past 262144 require scaling CONTEXTS grows 383K/512K, labelled in the menu, and the setup refuses a context past the trained 262,144 without --rope-scaling (the engine would refuse it too). The factor defaults to the smallest that covers the chosen context (1.5 at 393K, 2 at 524K) and lands in the engine args like every other flag. --- setup.py | 34 ++++++++++++++++++++++++++++++---- 1 file changed, 30 insertions(+), 4 deletions(-) diff --git a/setup.py b/setup.py index e05cda39..be4e7032 100644 --- a/setup.py +++ b/setup.py @@ -19,7 +19,8 @@ What the first run does (each step is skipped when it is already done): 6. prepares the model for Strata and fetches the MTP draft layer (~5 GB, from the original Qwen checkpoint) 7. writes run-.bat / run-.sh and starts the model -Options: --family qwen|swift, --model Q2_0|IQ2_XS|IQ3_XXS|IQ3_S, --context 32768, --vision yes|no|gpu|cpu, --port 8080, --yes (recommended +Options: --family qwen|swift, --model Q2_0|IQ2_XS|IQ3_XXS|IQ3_S, --context 32768, --rope-scaling none|linear|yarn +(--rope-scale F, for contexts past the trained 262144), --vision yes|no|gpu|cpu, --port 8080, --yes (recommended answers, no questions), --setup (install another model / change settings instead of starting), --no-start, --host 0.0.0.0 --api-key KEY (reach it from other devices on your network), --experimental-speed-projection on|off (EXPERIMENTAL, off by default), @@ -77,7 +78,9 @@ MODELS = { "IQ1_M": {"about": "the Coder's only size: half the experts, stored like IQ3_S (3.5 bits)", "download_gb": 58.4, "ram_gb": 32, "arena_gb": 23.4, "families": ("coder",)}, } -CONTEXTS = [8192, 32768, 65536, 131072, 262144] +# Contexts past 262144 (the model's trained length) extend it by rope scaling - the engine refuses them +# without --rope-scaling, and the setup adds the flag when the chosen context needs it (below). +CONTEXTS = [8192, 32768, 65536, 131072, 262144, 393216, 524288] # The model families: the same architecture, weights in the same three GSQ-RCO sizes, different files. FAMILIES = { "qwen": {"title": "Qwen3.8-Flash-Next", "by": "Qwen; GSQ-RCO quants by ISTA-DASLab", @@ -1588,6 +1591,11 @@ def main() -> int: ap.add_argument("--family", choices=list(FAMILIES), help="qwen = Qwen3.8-Flash-Next, swift = Swift 1.5") ap.add_argument("--model", choices=list(MODELS)) ap.add_argument("--context", type=int) + ap.add_argument("--rope-scaling", choices=["none", "linear", "yarn"], + help="extend the context past the model's trained 262144: linear (position interpolation) or " + "yarn, llama.cpp's types; required for --context 393216/524288") + ap.add_argument("--rope-scale", type=float, help="the extension factor for --rope-scaling (default 2 when a " + "scaled context is chosen without one)") ap.add_argument("--kv", choices=["int8", "q4_0", "k8v4"], help="KV cache precision above 8K context: int8 (default), q4_0 (half the memory, a little less " "precise) or k8v4 (hybrid: INT8 K + 4-bit V, 816 B/cell)") @@ -1851,8 +1859,24 @@ def main() -> int: say(" Context length = how much text the model can see at once (your chat, files, tool output).") say(" Longer needs more VRAM for it, so fewer experts fit on the GPU:") for i, c in enumerate(CONTEXTS, 1): - say(f" {i}) {c // 1024}K tokens" + (" (recommended for your GPU)" if c == rec_ctx else "")) - ctx = CONTEXTS[int(ask("Context?", [str(i) for i in range(1, 6)], str(CONTEXTS.index(rec_ctx) + 1), a.yes)) - 1] + note = (" (recommended for your GPU)" if c == rec_ctx else "") + \ + (" (needs rope scaling)" if c > 262144 else "") + say(f" {i}) {c // 1024}K tokens{note}") + ctx = CONTEXTS[int(ask("Context?", [str(i) for i in range(1, len(CONTEXTS) + 1)], + str(CONTEXTS.index(rec_ctx) + 1), a.yes)) - 1] + if ctx > 262144 and a.rope_scaling in (None, "none"): + fail(f"a {ctx // 1024}K context is past the model's trained 262144: pass --rope-scaling linear or yarn " + "(the engine scales the rotary angles; see docs/DETAILS.md)") + rope_scale = a.rope_scale + if ctx > 262144 and rope_scale is None: + # the smallest factor that covers the chosen context, on the safe side + rope_scale = 1.5 if ctx <= 393216 else 2.0 + ok(f"rope scaling: factor {rope_scale:g} (covers {ctx // 1024}K; override with --rope-scale)") + elif rope_scale is not None and a.rope_scaling in (None, "none"): + fail("--rope-scale needs --rope-scaling linear or yarn") + if a.rope_scaling not in (None, "none") and rope_scale is None: + rope_scale = 2.0 + ok("rope scaling: factor 2 (override with --rope-scale)") # The experts' arena plus the context's KV (in RAM from 64K up: ~13.7 KB/token at 8 bits) must fit, with room # for everything else. Counted, not a fixed 90 GB: 24 GB of room keeps the rule for 64 GB PCs as it was (128K # for both 3-bit models), while a box with ~84 GB keeps the 262K it asked for (measured: a Colab A100-40G runs @@ -2026,6 +2050,8 @@ def main() -> int: "--expert-profile", str(ROOT / "data" / fam.get("profile", "expert-profile.bin")), "--expert-cache", "auto", "--prefill", "auto", "--spec", "4", "--spec-min-p", "0.5", "--mtp", str(rt), "--max-context", str(ctx)] + if a.rope_scaling not in (None, "none"): + args += ["--rope-scaling", a.rope_scaling, "--rope-scale", f"{rope_scale:g}"] if ctx > 8192: args += ["--kv", kv] if low_ram: From c1d061faa926692719a8864cb15bffbd056ddd89 Mon Sep 17 00:00:00 2001 From: Jakub Luwierski Date: Mon, 28 Sep 2026 21:09:14 +0200 Subject: [PATCH 05/18] docs: context extension (rope scaling) DETAILS.md gains the 'Context extension' subsection - what linear and yarn do, the setup path (383K/512K in the context menu pick the factor themselves), the engine flags with llama.cpp's names and their defaults, why the scaling is fixed for the whole run (K sits in the cache post-RoPE), and the one honest caveat: inside the trained range a scaled run is a slightly different model, and the recall numbers are text-only at one depth. Troubleshooting grows the row for the refusal a context past 262,144 now raises without the flag; README points the context question at it. --- README.md | 4 +++- docs/DETAILS.md | 23 +++++++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 2df0838c..d72bb816 100644 --- a/README.md +++ b/README.md @@ -102,7 +102,9 @@ App). Everything else - Python, the engine, the model - is set up for you. 2. Double-click **`START-HERE.bat`**. 3. Answer a few questions - or just press Enter each time for the recommended choice: - **Which model and size?** The original or Swift 1.5, and Q2_0, IQ2_XS, IQ3_XXS or IQ3_S - see [above](#which-model-should-i-pick) - - **How much context?** How much text it can keep in mind at once (it suggests one for your card) + - **How much context?** How much text it can keep in mind at once (it suggests one for your card). 384K and + 512K extend the model past its trained 262K by rope scaling - the setup adds the flag itself + ([details](docs/DETAILS.md)) - **Images?** Whether it should also read pictures - **Experimental speed projection?** Off unless you say yes - [read what it does](docs/DETAILS.md#experimental-speed-projection-experimental-off-by-default) first diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 1217072e..429dbbd3 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -428,6 +428,28 @@ it needs, prefer read-only tools, and don't add servers you don't trust. The too page itself (a request with another site's Origin or without a JSON content type is refused); if Strata is reachable from other devices, set an API key. +**Context extension (rope scaling, engine 0.1.18).** The model trains 262,144 positions of rotary base +1e7; the context past that stays coherent by rescaling the rotation angles, with llama.cpp's types and +flag names. `linear` is Position Interpolation (every angle shrunk by the factor); `yarn` keeps the +high-frequency angles and interpolates the low-frequency ones, with the magnitude correction that keeps +the attention temperature where training put it. Scaled contexts also need proportionally more VRAM/RAM +for the KV cache and the rope tables (~13 KB and ~0.26 KB per token). + +- setup: `START-HERE.bat --setup --context 393216` asks nothing extra - it picks the factor for you + (`--rope-scale` overrides; 393K wants 1.5, 524K wants 2). Contexts past 262,144 refuse to start without + `--rope-scaling`. +- engine: `--rope-scaling none|linear|yarn`, `--rope-scale F`, and the raw ggml knobs `--rope-freq-base`, + `--rope-freq-scale`, `--yarn-orig-ctx` (default 262,144), `--yarn-ext-factor`, `--yarn-attn-factor`, + `--yarn-beta-fast` (32), `--yarn-beta-slow` (1). The model file's `rope.scaling.*` keys, when a + fine-tune ships them, are the defaults the flags override. + +The scaling is fixed for the whole run - the engine stores keys in its cache after rotating them, so one +cache must never mix two scalings, and there is no per-request form. Within the trained 262,144 a scaled +run is a different (very slightly perturbed) model: `yarn`'s magnitude correction applies everywhere, not +only past the trained end. Needle recall past the trained end passes (262k and 512k prompt probes at +linear 2 and yarn 2, mid-depth, `tools/needle_bench.py`); pictures read the same scaled table (their +(t, h, w) positions feed it), which is expected to compose but unmeasured - the recall runs are text. + --- ## Images (vision) @@ -557,6 +579,7 @@ the document, +0.4% on the chat. Details: `bench/results/2026-09-27-esp/`. | `the engine stopped unexpectedly (exit code ...)` | The engine process ended mid-answer - usually out of RAM (Linux ends the biggest program: `sudo dmesg \| grep -i -E 'killed process\|out of memory'`). The next request starts it again by itself. If it repeats: close other programs or pick a smaller size. The server also warns at start when the model's experts leave less than ~6 GB of RAM for everything else. | | Slow output, disk light busy | Not enough free RAM: close other programs, or choose Q2_0 / IQ2_XS. | | `prompt ... exceeds the context` | The request is longer than the context you chose: run setup again with a bigger `--context`. | +| `past the model's trained 262144` (setup) / the engine refuses a context over 262,144 | A context past the trained one needs rope scaling (engine 0.1.18+): pass `--rope-scaling linear` or `yarn`, or let setup pick it (`START-HERE.bat --setup --context 393216`). | | Slower than the tables | The monitor plugged into the GPU and other GPU programs take VRAM from the expert cache; RAM running below its rated speed (enable EXPO/XMP in the BIOS) slows the CPU half. | | `this server was started without the vision encoder` | The model was set up for text only: run setup again with `--vision gpu`. | | A picture is refused or `cannot read the image` | The file is not a picture Pillow can open (JPEG, PNG, WebP, GIF, BMP, TIFF, AVIF work). | From c7d2766528a62419d46f072a65c99a9a2da63d5b Mon Sep 17 00:00:00 2001 From: Jakub Luwierski Date: Tue, 29 Sep 2026 14:30:43 +0200 Subject: [PATCH 06/18] generate: an explicit --rope-scaling none or --rope-scale 1 overrides the GGUF rope keys The defaults collided with the opt-outs: "none" was both the untouched --rope-scaling default and the explicit switch-off, and 1.0 the same for --rope-scale, so qwen4exp.rope.scaling.type/factor from the model file won even against an explicit flag - the opposite of the stated precedence (and of docs/DETAILS.md). Now the empty string and 0 mean the flag is absent (the same sentinel idiom as --rope-freq-base 0 and --yarn-orig-ctx 0), the model file fills only what no explicit flag named, and `none` / `1` are the opt-outs they read as. The resolution moves above the weight pipeline: the config needs only the CLI and the model file's metadata, its one hard constraint (set before session_init builds the table and the graphs capture the constants) is unchanged, and a bad rope key now dies before the shards are scanned. Checked on the bench machine against a synthetic GGUF carrying rope.scaling.type yarn / factor 4: the flags absent -> yarn 4; --rope-scaling none -> no scaling; --rope-scale 1 -> yarn, factor 1, mscale 1; explicit linear 2 -> linear 2; a GGUF type other than none/linear/yarn dies before the weight scan. The real artifact (no rope keys) starts and generates unchanged, and rope_parity stays green. --- src/program/generate.cpp | 160 +++++++++++++++++++++------------------ 1 file changed, 87 insertions(+), 73 deletions(-) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index cb0f9d50..83310c56 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -132,9 +132,10 @@ struct Options { /// THE CONTEXT EXTENSION (rope scaling, rope_scaling.hpp). These knobs resolve to ONE process config, /// set once before `session_init` builds the rope table and the graphs capture the kernels. There is /// deliberately no per-request form: K sits in the cache POST-RoPE, so one cache must never mix two - /// scalings. Precedence: CLI over the model file's rope keys over the struct defaults. - std::string rope_scaling = "none"; ///< --rope-scaling none|linear|yarn (llama.cpp's names) - double rope_scale = 1.0; ///< --rope-scale F: the extension factor; 1 = off + /// scalings. Precedence: an EXPLICIT flag over the model file's rope keys over the struct defaults - + /// `none` and `1` are explicit values (the opt-outs), the absent flag is not. + std::string rope_scaling; ///< --rope-scaling none|linear|yarn (llama.cpp's names); empty = the flag is absent + double rope_scale = 0; ///< --rope-scale F: the extension factor; 0 = the flag is absent (the model file's, else 1 = off) double rope_freq_base = 0; ///< --rope-freq-base N: 0 = the model's (1e7) double rope_freq_scale = 0; ///< --rope-freq-scale F: the raw ggml knob; 0 = 1/--rope-scale double yarn_orig_ctx = 0; ///< --yarn-orig-ctx N: 0 = the model's, else 262144 @@ -373,10 +374,12 @@ void usage() { " --expert-cache-cpu-order experimental GPU expert reduction matching CPU order\n" " --max-new N tokens to generate (default 16)\n" " --max-context N KV/state capacity (default 4096)\n" - " --rope-scaling T extend the context past the trained one: none (default), linear\n" + " --rope-scaling T extend the context past the trained one: none, linear\n" " (position interpolation) or yarn - llama.cpp's types and names.\n" - " Fixed at startup: K in the cache is post-RoPE, so one run one scaling\n" - " --rope-scale F the extension factor for linear/yarn (default 1 = off)\n" + " Default: the model file's rope keys, else none. Fixed at startup:\n" + " K in the cache is post-RoPE, so one run one scaling\n" + " --rope-scale F the extension factor for linear/yarn (default: the model file's\n" + " factor, else 1 = off)\n" " --rope-freq-base N the raw ggml knobs: the frequency base (0 = the model's 1e7) and\n" " --rope-freq-scale F the angle shrink (0 = 1/--rope-scale)\n" " --yarn-orig-ctx N the trained context the correction targets (0 = 262144)\n" @@ -1316,15 +1319,18 @@ int main(int argc, char** argv) { strata::kernels::RopeScaling rope_cfg; // type filled here; the rest at the resolution below { using RST = strata::kernels::RopeScalingType; + // an absent --rope-scaling (the empty default) leaves the type to the model file's rope keys, + // resolved below; anything present must be one of the three names if (o.rope_scaling == "none") rope_cfg.type = RST::None; else if (o.rope_scaling == "linear") rope_cfg.type = RST::Linear; else if (o.rope_scaling == "yarn") rope_cfg.type = RST::YaRN; - else { + else if (!o.rope_scaling.empty()) { std::fprintf(stderr, "strata generate: --rope-scaling must be none, linear or yarn (got '%s')\n", o.rope_scaling.c_str()); return 2; } - if (o.rope_scale < 1.0) { + // 0 is the absent default; an explicit factor must extend, not shrink + if (o.rope_scale > 0 && o.rope_scale < 1.0) { std::fprintf(stderr, "strata generate: --rope-scale %g must be >= 1 (it extends the context, not shrinks it)\n", o.rope_scale); return 2; @@ -1435,6 +1441,79 @@ int main(int argc, char** argv) { std::fprintf(stderr, "strata generate: this CPU has no AVX-512: the expert kernels run on %s " "(multi-token for the i-quant gate/up rows)\n", std::getenv("STRATA_NO_IQ256") == nullptr ? "AVX-2" : "ggml-cpu vec_dot (STRATA_NO_IQ256 set)"); + strata::core::ModelGeometry g; // canonical defaults; the model file overrides the MoE shape below + int64_t K = 10; + // THE ROPE CONFIG RESOLVES HERE, BEFORE ANY WEIGHT MOVES - the CLI and the model file have both spoken, + // and `session_init` below builds the rope table from it and captures the kernels reading its constants + // (rope_scaling.hpp); the only hard constraint is "set before that", and dying on a bad rope key beats + // scanning gigabytes of shards first. Precedence: an EXPLICIT flag over the model file's rope keys over + // the struct defaults. The empty --rope-scaling and the 0 --rope-scale mean the flag is absent, so the + // model file decides; an explicit value - `none` and `1` included, the opt-outs - wins over the model file. + { + // The model file's rope keys (llama.cpp's names under the arch prefix), when it carries any - the + // artifact today ships none, so this is a no-op defaults channel for future fine-tunes. + std::string gguf_rope_type; + double gguf_rope_base = 0, gguf_rope_factor = 0, gguf_rope_orig_ctx = 0; + if (!o.native_preset.empty()) { + // a pruned variant (GSQ-RCO Coder) ships fewer experts than the canonical 512x10; the model file + // is the authority on its own MoE shape - everything else in the geometry is unchanged + try { + strata::GgufFile model_gguf(o.native_preset); + if (const strata::MetaValue* v = model_gguf.get("qwen4exp.expert_count")) g.n_expert = (int64_t) v->u; + if (const strata::MetaValue* v = model_gguf.get("qwen4exp.expert_used_count")) K = (int64_t) v->u; + if (const strata::MetaValue* v = model_gguf.get("qwen4exp.rope.freq_base")) gguf_rope_base = v->num(); + if (const strata::MetaValue* v = model_gguf.get("qwen4exp.rope.scaling.type")) gguf_rope_type = v->s; + if (const strata::MetaValue* v = model_gguf.get("qwen4exp.rope.scaling.factor")) gguf_rope_factor = v->num(); + if (const strata::MetaValue* v = model_gguf.get("qwen4exp.rope.scaling.original_context_length")) + gguf_rope_orig_ctx = v->num(); + } catch (const std::exception& e) { + std::fprintf(stderr, "strata generate: reading the model's expert shape from %s: %s\n", + o.native_preset.c_str(), e.what()); + return 1; + } + } + using RST = strata::kernels::RopeScalingType; + if (!o.rope_scaling.empty()) { + // the early validation pinned the spelling; `none` here is the CLI opting OUT of the model file's keys + if (o.rope_scaling == "linear") rope_cfg.type = RST::Linear; + else if (o.rope_scaling == "yarn") rope_cfg.type = RST::YaRN; + else rope_cfg.type = RST::None; + } else if (!gguf_rope_type.empty()) { + if (gguf_rope_type == "linear") rope_cfg.type = RST::Linear; + else if (gguf_rope_type == "yarn") rope_cfg.type = RST::YaRN; + else if (gguf_rope_type != "none") { + std::fprintf(stderr, "strata generate: %s carries rope.scaling.type '%s' - none, linear or yarn only\n", + o.native_preset.c_str(), gguf_rope_type.c_str()); + return 2; + } + } + if (o.rope_scale > 0) rope_cfg.factor = o.rope_scale; // an explicit factor, 1 included + else if (gguf_rope_factor > 1.0) rope_cfg.factor = gguf_rope_factor; + if (o.rope_freq_base > 0) rope_cfg.freq_base = o.rope_freq_base; + else if (gguf_rope_base > 1.0) rope_cfg.freq_base = gguf_rope_base; + if (o.yarn_orig_ctx > 0) rope_cfg.orig_ctx = o.yarn_orig_ctx; + else if (gguf_rope_orig_ctx >= 1) rope_cfg.orig_ctx = gguf_rope_orig_ctx; + rope_cfg.freq_scale_in = o.rope_freq_scale; + rope_cfg.ext_factor = o.yarn_ext_factor >= 0 ? o.yarn_ext_factor + : (rope_cfg.type == RST::YaRN ? 1.0 : 0.0); + rope_cfg.attn_factor = o.yarn_attn_factor; + rope_cfg.beta_fast = o.yarn_beta_fast; + rope_cfg.beta_slow = o.yarn_beta_slow; + strata::kernels::rope_scaling_set(rope_cfg); + if (rope_cfg.type != RST::None) { + const char* tn = rope_cfg.type == RST::YaRN ? "yarn" : "linear"; + std::fprintf(stderr, + "strata generate: rope scaling %s, factor %.6g (freq_scale %.6g, base %.6g, mscale %.6f), " + "--max-context %lld against a trained context of %.0f\n", + tn, rope_cfg.factor, rope_cfg.freq_scale(), rope_cfg.freq_base, rope_cfg.mscale(), + (long long) o.max_context, rope_cfg.orig_ctx); + if ((double) o.max_context <= rope_cfg.orig_ctx) + std::fprintf(stderr, + "strata generate: note: the context is within the trained %.0f - the angles barely move, " + "but YaRN's magnitude correction applies everywhere\n", + rope_cfg.orig_ctx); + } + } strata::core::NativeEmbed native_embed; if (native_pack) { if (o.native_preset.empty() || o.spec < 2 || o.keep_canonical || @@ -1536,71 +1615,6 @@ int main(int argc, char** argv) { strata::kernels::mrope_table_set(d_mrope); } strata::kernels::ple_set_native_postops(o.native_ple_postops); - strata::core::ModelGeometry g; // canonical defaults; the model file overrides the MoE shape below - int64_t K = 10; - // The model file's rope keys (llama.cpp's names under the arch prefix), when it carries any - the - // artifact today ships none, so this is a no-op defaults channel for future fine-tunes. - std::string gguf_rope_type; - double gguf_rope_base = 0, gguf_rope_factor = 0, gguf_rope_orig_ctx = 0; - if (!o.native_preset.empty()) { - // a pruned variant (GSQ-RCO Coder) ships fewer experts than the canonical 512x10; the model file - // is the authority on its own MoE shape - everything else in the geometry is unchanged - try { - strata::GgufFile model_gguf(o.native_preset); - if (const strata::MetaValue* v = model_gguf.get("qwen4exp.expert_count")) g.n_expert = (int64_t) v->u; - if (const strata::MetaValue* v = model_gguf.get("qwen4exp.expert_used_count")) K = (int64_t) v->u; - if (const strata::MetaValue* v = model_gguf.get("qwen4exp.rope.freq_base")) gguf_rope_base = v->num(); - if (const strata::MetaValue* v = model_gguf.get("qwen4exp.rope.scaling.type")) gguf_rope_type = v->s; - if (const strata::MetaValue* v = model_gguf.get("qwen4exp.rope.scaling.factor")) gguf_rope_factor = v->num(); - if (const strata::MetaValue* v = model_gguf.get("qwen4exp.rope.scaling.original_context_length")) - gguf_rope_orig_ctx = v->num(); - } catch (const std::exception& e) { - std::fprintf(stderr, "strata generate: reading the model's expert shape from %s: %s\n", - o.native_preset.c_str(), e.what()); - return 1; - } - } - // THE ROPE CONFIG RESOLVES HERE - the CLI and the model file have both spoken, and `session_init` - // below builds the rope table from it and captures the kernels reading its constants (rope_scaling.hpp). - // Precedence: CLI over model file over the struct defaults. An explicit `--rope-scaling none` and the - // untouched default are the same choice: the CLI opt-out wins over the model file too. - { - using RST = strata::kernels::RopeScalingType; - if (rope_cfg.type == RST::None && !gguf_rope_type.empty()) { - if (gguf_rope_type == "linear") rope_cfg.type = RST::Linear; - else if (gguf_rope_type == "yarn") rope_cfg.type = RST::YaRN; - else if (gguf_rope_type != "none") { - std::fprintf(stderr, "strata generate: %s carries rope.scaling.type '%s' - none, linear or yarn only\n", - o.native_preset.c_str(), gguf_rope_type.c_str()); - return 2; - } - } - rope_cfg.factor = (o.rope_scale == 1.0 && gguf_rope_factor > 1.0) ? gguf_rope_factor : o.rope_scale; - if (o.rope_freq_base > 0) rope_cfg.freq_base = o.rope_freq_base; - else if (gguf_rope_base > 1.0) rope_cfg.freq_base = gguf_rope_base; - if (o.yarn_orig_ctx > 0) rope_cfg.orig_ctx = o.yarn_orig_ctx; - else if (gguf_rope_orig_ctx >= 1) rope_cfg.orig_ctx = gguf_rope_orig_ctx; - rope_cfg.freq_scale_in = o.rope_freq_scale; - rope_cfg.ext_factor = o.yarn_ext_factor >= 0 ? o.yarn_ext_factor - : (rope_cfg.type == RST::YaRN ? 1.0 : 0.0); - rope_cfg.attn_factor = o.yarn_attn_factor; - rope_cfg.beta_fast = o.yarn_beta_fast; - rope_cfg.beta_slow = o.yarn_beta_slow; - strata::kernels::rope_scaling_set(rope_cfg); - if (rope_cfg.type != RST::None) { - const char* tn = rope_cfg.type == RST::YaRN ? "yarn" : "linear"; - std::fprintf(stderr, - "strata generate: rope scaling %s, factor %.6g (freq_scale %.6g, base %.6g, mscale %.6f), " - "--max-context %lld against a trained context of %.0f\n", - tn, rope_cfg.factor, rope_cfg.freq_scale(), rope_cfg.freq_base, rope_cfg.mscale(), - (long long) o.max_context, rope_cfg.orig_ctx); - if ((double) o.max_context <= rope_cfg.orig_ctx) - std::fprintf(stderr, - "strata generate: note: the context is within the trained %.0f - the angles barely move, " - "but YaRN's magnitude correction applies everywhere\n", - rope_cfg.orig_ctx); - } - } // before session_init: every graph captured from here on has the vector's kernels where it applies std::string cvec_summary = "0"; if (!o.cvec_files.empty()) { From f4ae11b736b6c46b1900c89c4d0e1319ea2171bd Mon Sep 17 00:00:00 2001 From: Jakub Luwierski Date: Tue, 29 Sep 2026 14:30:49 +0200 Subject: [PATCH 07/18] bench: rope-scaling needles past the trained 262K (linear 2, yarn 2) The first end-to-end check that a scaled run recalls past the trained end: 8 of 8 probes found the needle at mid-depth, temperature 0 - 1k/32k/128k on the stock model (arm A), 262k and 512k prompts on linear factor 2 (arm B) and yarn factor 2 (arm C), 512k being 2.01x the trained 262,144. The yarn 262k probe was repeated green after the rebase onto 0.1.20, next to the per-arm engine and server logs and the launch recipes. What it does not establish is written down in the README: one depth, one needle per length, and no long-document perplexity with and without scaling at 262K yet - the one open measurement. --- .../results/2026-09-28-rope-scaling/README.md | 49 +++++++ .../config-A-none-262144.json | 38 ++++++ .../config-B-linear2.json | 42 ++++++ .../config-C-yarn2.json | 42 ++++++ .../2026-09-28-rope-scaling/kv-sweep-tgs.json | 121 ++++++++++++++++++ .../needle-A-none.json | 29 +++++ .../needle-B-linear2-512k.json | 11 ++ .../needle-B-linear2.json | 16 +++ .../needle-C-yarn2-rebased.json | 11 ++ .../needle-C-yarn2.json | 20 +++ 10 files changed, 379 insertions(+) create mode 100644 bench/results/2026-09-28-rope-scaling/README.md create mode 100644 bench/results/2026-09-28-rope-scaling/config-A-none-262144.json create mode 100644 bench/results/2026-09-28-rope-scaling/config-B-linear2.json create mode 100644 bench/results/2026-09-28-rope-scaling/config-C-yarn2.json create mode 100644 bench/results/2026-09-28-rope-scaling/kv-sweep-tgs.json create mode 100644 bench/results/2026-09-28-rope-scaling/needle-A-none.json create mode 100644 bench/results/2026-09-28-rope-scaling/needle-B-linear2-512k.json create mode 100644 bench/results/2026-09-28-rope-scaling/needle-B-linear2.json create mode 100644 bench/results/2026-09-28-rope-scaling/needle-C-yarn2-rebased.json create mode 100644 bench/results/2026-09-28-rope-scaling/needle-C-yarn2.json diff --git a/bench/results/2026-09-28-rope-scaling/README.md b/bench/results/2026-09-28-rope-scaling/README.md new file mode 100644 index 00000000..e1e2e477 --- /dev/null +++ b/bench/results/2026-09-28-rope-scaling/README.md @@ -0,0 +1,49 @@ +# Rope scaling: needle recall past the trained 262K + +The feature (engine 0.1.18): `--rope-scaling none|linear|yarn` extends the context past the model's +trained 262,144 positions by rescaling the rotary angles - llama.cpp's types, ggml's `rope_yarn` +arithmetic, one process config applied at the cos/sin table (default path) and as kernel constants +(`--native-rope`, the native indexer, prefill). The three tables here are the first end-to-end check +that a scaled run actually recalls past the trained end. + +**Hardware:** RTX 4070 Ti SUPER 16 GB, Ryzen 9 5900X (no AVX-512 - the IQ3_XXS native pack runs its +expert kernels on AVX-2), 125 GB RAM, Linux. **Engine:** this branch built from source (the log records +`rope scaling ... --max-context ... against a trained context of 262144` at startup). The runs below +were taken on the rope tree built over the 0.1.17-era base; the branch then rebased onto main (engine +0.1.20) - the drift touches none of the rope files - and the rebase was re-validated: `rope_parity` +green, a 64-token greedy run token-identical to the plain 0.1.20 build, and the yarn 262k probe +repeated green (see the last table row). Baseline arm A also re-checked the default is the stock +model: a 64-token greedy run produces the same token ids as the ready-made 0.1.17 engine, and +`rope_parity` holds the `none` table bit-identical to the pre-scaling builder. +**Method:** `tools/needle_bench.py` against a running server (launch recipes in `config-*.json`), +`temperature 0`, thinking off, depth 50%, one probe per length. + +| Arm | Scaling | Context | Probe | Prompt tokens | Result | Probe time | +| --- | --- | --- | --- | --- | --- | --- | +| A | none | 262,144 | 1k @ 50% | 1,442 | FOUND | 4 s | +| A | none | 262,144 | 32k @ 50% | 31,763 | FOUND | 27 s | +| A | none | 262,144 | 128k @ 50% | 128,328 | FOUND | 86 s | +| B | linear, factor 2 | 560,000 | 262k @ 50% | 274,222 | FOUND | 232 s | +| B | linear, factor 2 | 560,000 | 512k @ 50% | 527,051 | FOUND | 619 s | +| C | yarn, factor 2 | 560,000 | 262k @ 50% | 274,215 | FOUND | 236 s | +| C | yarn, factor 2 | 560,000 | 512k @ 50% | 526,988 | FOUND | 615 s | +| C | yarn, factor 2 | 560,000 | 262k @ 50% (the rebase re-check) | 273,708 | FOUND | 235 s | + +All 8 of 8 probes found the needle; JSON per arm: `needle-A-none.json`, `needle-B-linear2.json`, +`needle-B-linear2-512k.json`, `needle-C-yarn2.json` (+ the rebase re-check in +`needle-C-yarn2-rebased.json`); server and engine logs alongside. + +What this establishes, and what it does not: + +- **Past the trained end the model still reads.** 512k probes are 2.01x the trained 262,144 - position + interpolation (B) and YaRN (C) both hold a mid-context lookup there. +- **Scaled runs within the trained range are a slightly different model.** `yarn`'s mscale applies at + every position (a 64-token greedy prompt diverges from the stock run after ~19 tokens); arm A is the + stock model, arms B/C are not, by design. +- **One depth, one needle, one machine.** A single probe per (length, arm) at depth 50% says "recall + works there", not "no degradation anywhere" - a full depth sweep and a longer-length ladder (768K, + 1M) on the bench machine (64 GB RAM there vs 125 GB here, so 262K IQ3_XXS fits either way) is the + natural follow-up. 512K prompts prefill at ~850-950 tokens/s on this card; the probe time is almost + entirely prefill. +- **The `560,000` context** in arms B/C is headroom for the needle harness's tokenizer overshoot + (a "512k" probe tokenizes to ~527k); 524,288 exactly would refuse the probe. diff --git a/bench/results/2026-09-28-rope-scaling/config-A-none-262144.json b/bench/results/2026-09-28-rope-scaling/config-A-none-262144.json new file mode 100644 index 00000000..528fc9f6 --- /dev/null +++ b/bench/results/2026-09-28-rope-scaling/config-A-none-262144.json @@ -0,0 +1,38 @@ +{ + "exe": "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata/build/strata", + "cwd": "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata", + "tokenizer": "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata-data/packs/iq3_xxs/tokenizer", + "model_name": "qwen3.8-flash-next-iq3_xxs-rope-scaling", + "lib_dirs": [ + "/usr/local/cuda/bin", + "/usr/local/cuda/lib64" + ], + "port": 8130, + "args": [ + "--pack", + "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata-data/packs/iq3_xxs", + "--native", + "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata-data/models/IQ3_XXS/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00001-of-00002.gguf", + "--ple-gguf", + "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata-data/models/IQ3_XXS/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00002-of-00002.gguf", + "--expert-profile", + "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata/data/expert-profile.bin", + "--expert-cache", + "auto", + "--prefill", + "auto", + "--spec", + "4", + "--spec-min-p", + "0.5", + "--mtp", + "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata-data/mtp/rt", + "--kv", + "int8", + "--kv-resident", + "32768", + "--max-context", + "262144" + ], + "log": "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata/bench/results/2026-09-28-rope-scaling/engine-A-none-262144.log" +} \ No newline at end of file diff --git a/bench/results/2026-09-28-rope-scaling/config-B-linear2.json b/bench/results/2026-09-28-rope-scaling/config-B-linear2.json new file mode 100644 index 00000000..30b31d7d --- /dev/null +++ b/bench/results/2026-09-28-rope-scaling/config-B-linear2.json @@ -0,0 +1,42 @@ +{ + "exe": "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata/build/strata", + "cwd": "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata", + "tokenizer": "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata-data/packs/iq3_xxs/tokenizer", + "model_name": "qwen3.8-flash-next-iq3_xxs-rope-scaling", + "lib_dirs": [ + "/usr/local/cuda/bin", + "/usr/local/cuda/lib64" + ], + "port": 8130, + "args": [ + "--pack", + "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata-data/packs/iq3_xxs", + "--native", + "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata-data/models/IQ3_XXS/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00001-of-00002.gguf", + "--ple-gguf", + "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata-data/models/IQ3_XXS/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00002-of-00002.gguf", + "--expert-profile", + "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata/data/expert-profile.bin", + "--expert-cache", + "auto", + "--prefill", + "auto", + "--spec", + "4", + "--spec-min-p", + "0.5", + "--mtp", + "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata-data/mtp/rt", + "--kv", + "int8", + "--kv-resident", + "32768", + "--max-context", + "560000", + "--rope-scaling", + "linear", + "--rope-scale", + "2" + ], + "log": "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata/bench/results/2026-09-28-rope-scaling/engine-B-linear2-524288.log" +} \ No newline at end of file diff --git a/bench/results/2026-09-28-rope-scaling/config-C-yarn2.json b/bench/results/2026-09-28-rope-scaling/config-C-yarn2.json new file mode 100644 index 00000000..6172a63a --- /dev/null +++ b/bench/results/2026-09-28-rope-scaling/config-C-yarn2.json @@ -0,0 +1,42 @@ +{ + "exe": "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata/build/strata", + "cwd": "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata", + "tokenizer": "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata-data/packs/iq3_xxs/tokenizer", + "model_name": "qwen3.8-flash-next-iq3_xxs-rope-scaling", + "lib_dirs": [ + "/usr/local/cuda/bin", + "/usr/local/cuda/lib64" + ], + "port": 8130, + "args": [ + "--pack", + "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata-data/packs/iq3_xxs", + "--native", + "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata-data/models/IQ3_XXS/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00001-of-00002.gguf", + "--ple-gguf", + "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata-data/models/IQ3_XXS/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00002-of-00002.gguf", + "--expert-profile", + "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata/data/expert-profile.bin", + "--expert-cache", + "auto", + "--prefill", + "auto", + "--spec", + "4", + "--spec-min-p", + "0.5", + "--mtp", + "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata-data/mtp/rt", + "--kv", + "int8", + "--kv-resident", + "32768", + "--max-context", + "560000", + "--rope-scaling", + "yarn", + "--rope-scale", + "2" + ], + "log": "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata/bench/results/2026-09-28-rope-scaling/engine-C-yarn2-524288.log" +} \ No newline at end of file diff --git a/bench/results/2026-09-28-rope-scaling/kv-sweep-tgs.json b/bench/results/2026-09-28-rope-scaling/kv-sweep-tgs.json new file mode 100644 index 00000000..526b7514 --- /dev/null +++ b/bench/results/2026-09-28-rope-scaling/kv-sweep-tgs.json @@ -0,0 +1,121 @@ +[ + { + "length": "128k", + "round": 0, + "kind": "decode", + "prompt_tok": 128401, + "read": 52, + "gen": 357, + "read_tok_s": 79.2, + "gen_tok_s": 56.3, + "drafts_ok": 182, + "drafts_all": 305, + "seg_blocks": 3284340, + "seg_mib": 370.0, + "seg_misses": 91744, + "seg_hit_pct": 97.207, + "kib_per_token": 1061.29 + }, + { + "length": "128k", + "round": 1, + "kind": "read", + "prompt_tok": 128357, + "read": 128357, + "gen": 24, + "read_tok_s": 1389.2, + "gen_tok_s": 41.7, + "drafts_ok": 11, + "drafts_all": 23, + "seg_blocks": -3253560, + "seg_mib": -391.7, + "seg_misses": -97147, + "seg_hit_pct": 97.014, + "kib_per_token": -3.12 + }, + { + "length": "128k", + "round": 1, + "kind": "decode", + "prompt_tok": 128402, + "read": 52, + "gen": 388, + "read_tok_s": 76.5, + "gen_tok_s": 54.6, + "drafts_ok": 195, + "drafts_all": 363, + "seg_blocks": 3752616, + "seg_mib": 463.5, + "seg_misses": 114911, + "seg_hit_pct": 96.938, + "kib_per_token": 1223.26 + }, + { + "length": "512k", + "round": 0, + "kind": "read", + "prompt_tok": 522983, + "read": 522983, + "gen": 24, + "read_tok_s": 868.4, + "gen_tok_s": 42.4, + "drafts_ok": 13, + "drafts_all": 16, + "seg_blocks": -3808056, + "seg_mib": -387.8, + "seg_misses": -96113, + "seg_hit_pct": 97.476, + "kib_per_token": -0.76 + }, + { + "length": "512k", + "round": 0, + "kind": "decode", + "prompt_tok": 523028, + "read": 52, + "gen": 402, + "read_tok_s": 63.3, + "gen_tok_s": 48.4, + "drafts_ok": 221, + "drafts_all": 348, + "seg_blocks": 3580056, + "seg_mib": 920.4, + "seg_misses": 228658, + "seg_hit_pct": 93.613, + "kib_per_token": 2344.5 + }, + { + "length": "512k", + "round": 1, + "kind": "read", + "prompt_tok": 522984, + "read": 522984, + "gen": 24, + "read_tok_s": 857.1, + "gen_tok_s": 35.5, + "drafts_ok": 9, + "drafts_all": 18, + "seg_blocks": -3555408, + "seg_mib": -905.8, + "seg_misses": -225016, + "seg_hit_pct": 93.671, + "kib_per_token": -1.77 + }, + { + "length": "512k", + "round": 1, + "kind": "decode", + "prompt_tok": 523029, + "read": 52, + "gen": 402, + "read_tok_s": 61.3, + "gen_tok_s": 42.8, + "drafts_ok": 192, + "drafts_all": 388, + "seg_blocks": 4005216, + "seg_mib": 1079.9, + "seg_misses": 268221, + "seg_hit_pct": 93.303, + "kib_per_token": 2750.79 + } +] \ No newline at end of file diff --git a/bench/results/2026-09-28-rope-scaling/needle-A-none.json b/bench/results/2026-09-28-rope-scaling/needle-A-none.json new file mode 100644 index 00000000..099bd36b --- /dev/null +++ b/bench/results/2026-09-28-rope-scaling/needle-A-none.json @@ -0,0 +1,29 @@ +[ + { + "length": "1k", + "depth": 50, + "prompt_tokens": 1442, + "seconds": 3.7, + "found": true, + "word": "meadow-copper-504", + "answer": "meadow-copper-504" + }, + { + "length": "32k", + "depth": 50, + "prompt_tokens": 31763, + "seconds": 27.5, + "found": true, + "word": "falcon-quartz-940", + "answer": "falcon-quartz-940" + }, + { + "length": "128k", + "depth": 50, + "prompt_tokens": 128328, + "seconds": 86.1, + "found": true, + "word": "willow-cobalt-696", + "answer": "willow-cobalt-696" + } +] \ No newline at end of file diff --git a/bench/results/2026-09-28-rope-scaling/needle-B-linear2-512k.json b/bench/results/2026-09-28-rope-scaling/needle-B-linear2-512k.json new file mode 100644 index 00000000..e93f21d4 --- /dev/null +++ b/bench/results/2026-09-28-rope-scaling/needle-B-linear2-512k.json @@ -0,0 +1,11 @@ +[ + { + "length": "512k", + "depth": 50, + "prompt_tokens": 527051, + "seconds": 619.0, + "found": true, + "word": "meadow-copper-504", + "answer": "meadow-copper-504" + } +] \ No newline at end of file diff --git a/bench/results/2026-09-28-rope-scaling/needle-B-linear2.json b/bench/results/2026-09-28-rope-scaling/needle-B-linear2.json new file mode 100644 index 00000000..7a987877 --- /dev/null +++ b/bench/results/2026-09-28-rope-scaling/needle-B-linear2.json @@ -0,0 +1,16 @@ +[ + { + "length": "262k", + "depth": 50, + "prompt_tokens": 274222, + "seconds": 232.2, + "found": true, + "word": "meadow-copper-504", + "answer": "meadow-copper-504" + }, + { + "length": "512k", + "depth": 50, + "error": "HTTP Error 400: Bad Request" + } +] \ No newline at end of file diff --git a/bench/results/2026-09-28-rope-scaling/needle-C-yarn2-rebased.json b/bench/results/2026-09-28-rope-scaling/needle-C-yarn2-rebased.json new file mode 100644 index 00000000..659f51a3 --- /dev/null +++ b/bench/results/2026-09-28-rope-scaling/needle-C-yarn2-rebased.json @@ -0,0 +1,11 @@ +[ + { + "length": "262k", + "depth": 50, + "prompt_tokens": 273708, + "seconds": 234.8, + "found": true, + "word": "meadow-copper-504", + "answer": "meadow-copper-504" + } +] \ No newline at end of file diff --git a/bench/results/2026-09-28-rope-scaling/needle-C-yarn2.json b/bench/results/2026-09-28-rope-scaling/needle-C-yarn2.json new file mode 100644 index 00000000..2dfa146d --- /dev/null +++ b/bench/results/2026-09-28-rope-scaling/needle-C-yarn2.json @@ -0,0 +1,20 @@ +[ + { + "length": "262k", + "depth": 50, + "prompt_tokens": 274215, + "seconds": 235.5, + "found": true, + "word": "meadow-copper-504", + "answer": "meadow-copper-504" + }, + { + "length": "512k", + "depth": 50, + "prompt_tokens": 526988, + "seconds": 615.0, + "found": true, + "word": "falcon-quartz-940", + "answer": "falcon-quartz-940" + } +] \ No newline at end of file From 9adfaa42e5dbb03a5ff7a8a4020243484c83a06f Mon Sep 17 00:00:00 2001 From: Jakub Luwierski Date: Tue, 29 Sep 2026 15:40:29 +0200 Subject: [PATCH 08/18] indexer: the batched append takes the one rope config, with a parity test The rebase onto 0.1.24 had brought the QSA indexer's C-2 chunk append, whose kernels rotated the pooled keys inline - cosf/sinf of the unscaled angle, no mscale - so a scaled prefill would have written indexer keys under a different rotation than the per-token append the decode path uses (rope_scaling.hpp's one-rotation rule, broken silently). The batch path now resolves freq_scale/corr_dims/mscale from the same RopeScaling the single append reads and rotates through the shared rope_scaled_angle; the raw freq_base parameter is gone from its signature. qsa_parity pins the contract the C-2 rework claimed: the batch append's whole end state (pooled, spare, tail ring, block_pos) is BIT-IDENTICAL to the sequential single appends', under none and yarn 2 alike, and the scaling is observable in the batched keys. --- src/kernels/qsa_parity.cpp | 69 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) diff --git a/src/kernels/qsa_parity.cpp b/src/kernels/qsa_parity.cpp index 5a8186dd..50558362 100644 --- a/src/kernels/qsa_parity.cpp +++ b/src/kernels/qsa_parity.cpp @@ -47,6 +47,7 @@ // 1e-3 for FP16 paths. That difference is the FP16 CACHE's cost, not the kernel's, and it is kept // separate so a kernel bug cannot hide inside it. #include "strata/kernels/qsa.hpp" +#include "strata/kernels/native_qsa_indexer.hpp" #include "strata/kernels/f16_bits.hpp" #include "strata/kernels/rope.hpp" @@ -1376,6 +1377,74 @@ int main(int argc, char** argv) { check(cudaGraphDestroy(g2), "gd"); } + // ================= the NATIVE indexer's batched append vs the sequential one ================= + // The prefill path appends a chunk in one native_qsa_indexer_append_batch call, the decode path appends + // token by token - and one cache must never be able to tell which path filled it (rope_scaling.hpp's + // one-rotation rule). So the batch's whole end state must be BIT-IDENTICAL to the sequential appends', + // under the two extremes of the scaling config: none (today's rotation) and yarn factor 2, whose mscale + // and corr-dims both kernels must take from the same RopeScaling. Eight cells: exactly two completed + // blocks, so the paths' end states agree on block_pos too (a mid-block chunk end leaves the sequential + // path pointing at the open block's base and the batch at the last completed one's - upstream C-2's own + // semantics, the same for every scaling). + { + std::printf("\n-- the native indexer's batched append vs the sequential one\n"); + const int64_t NB = 8; // exactly two complete blocks of r=4 + const int32_t BASE = 100; // positions 100..107, not cell indices 0..7 + const int64_t MC = 1024; // the capacity both sides validate against + std::vector raws((size_t) NB * IDXD); + for (int64_t t = 0; t < NB; ++t) + for (int64_t d = 0; d < IDXD; ++d) + raws[(size_t) t * IDXD + d] = (float) (gauss(rng) * std::pow(4.0, (double) (t % 4))); + cudaStream_t cs = nullptr; + check(cudaStreamCreate(&cs), "cs"); + std::vector none_pooled; + for (int variant = 0; variant < 2; ++variant) { + strata::kernels::RopeScaling sc; + if (variant == 1) { sc.type = strata::kernels::RopeScalingType::YaRN; sc.factor = 2.0; sc.ext_factor = 1.0; } + const size_t prows = (size_t) (MC / R + 1) * IDXD, trows = (size_t) (R - 1) * IDXD; + Dev pooledA(prows), deadA(IDXD), tailA(trows), pooledB(prows), deadB(IDXD), tailB(trows); + Dev bposA(1), bposB(1), dpos(1); + for (Dev* dp : {&pooledA, &deadA, &tailA, &pooledB, &deadB, &tailB}) + check(cudaMemset(dp->p, 0, dp == &pooledA || dp == &pooledB ? prows * 4 + : dp == &deadA || dp == &deadB ? IDXD * 4 : trows * 4), "zero"); + check(cudaMemset(bposA.p, 0, 4), "zero"); check(cudaMemset(bposB.p, 0, 4), "zero"); + Dev draw((size_t) IDXD), drawAll; + drawAll.put(raws); + strata::kernels::QsaIndexerBuffers bufsA{tailA.p, deadA.p, pooledA.p, bposA.p}; + strata::kernels::QsaIndexerBuffers bufsB{tailB.p, deadB.p, pooledB.p, bposB.p}; + for (int64_t t = 0; t < NB; ++t) { // the sequential side: one cell, its device position + check(cudaMemcpy(draw.p, &raws[(size_t) t * IDXD], (size_t) IDXD * 4, cudaMemcpyHostToDevice), "raw"); + const int32_t tp = (int32_t) t; + check(cudaMemcpy(dpos.p, &tp, 4, cudaMemcpyHostToDevice), "pos"); + strata::kernels::native_qsa_indexer_append(draw.p, dpos.p, BASE, dw_kn.p, EPS, bufsA, S, MC, sc, cs); + } + strata::kernels::native_qsa_indexer_append_batch(drawAll.p, NB, 0, BASE, dw_kn.p, EPS, bufsB, S, MC, sc, cs); + check(cudaStreamSynchronize(cs), "sync"); + const std::vector pa = pooledA.get(prows), pb = pooledB.get(prows); + const std::vector da = deadA.get((size_t) IDXD), db = deadB.get((size_t) IDXD); + const std::vector ta = tailA.get(trows), tbb = tailB.get(trows); + const std::vector ba = bposA.get(1), bb = bposB.get(1); + long long bad = 0; + for (size_t i = 0; i < pa.size(); ++i) bad += pa[i] != pb[i]; + for (size_t i = 0; i < da.size(); ++i) bad += da[i] != db[i]; + for (size_t i = 0; i < ta.size(); ++i) bad += ta[i] != tbb[i]; + bad += ba[0] != bb[0]; + std::printf(" %-44s %s (%lld of %zu state values differ)\n", + variant == 0 ? "batch vs sequential, none" : "batch vs sequential, yarn 2", + bad ? "*** WRONG ***" : "bit-identical", bad, pa.size() + da.size() + ta.size() + 1); + if (bad) ++g_bad; + if (variant == 0) none_pooled = pa; + else { + int differ = 0; + for (size_t i = 0; i < pa.size(); ++i) differ += pa[i] != none_pooled[i]; + std::printf(" %-44s %d of %zu pooled values moved\n", "the scaling is visible in the batched keys", + differ, pa.size()); + if (!differ) { std::printf(" *** the batched append ignored its scaling ***\n"); ++g_bad; } + } + } + check(cudaStreamDestroy(cs), "csd"); + } + std::printf("\nqsa: %d failures\n", g_bad); if (g_bad) return 1; if (selftest) std::printf("qsa_parity OK\n"); From 9b83998d9d11c39950dbbdaed10070014543ddee Mon Sep 17 00:00:00 2001 From: Jakub Luwierski Date: Tue, 29 Sep 2026 16:56:57 +0200 Subject: [PATCH 09/18] setup: the documented automatic rope configuration actually happens now MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The comment said the setup adds the flag when the chosen context needs it; the code called fail(). `START-HERE.bat --setup --context 393216` - the command the docs give - stopped instead of configuring. Now an omitted --rope-scaling with a past-trained context resolves the config itself: yarn (llama.cpp's extension method, recall-tested here at 512K; one question when interactive, the silent default with --yes) and the smallest covering factor (1.5 at 384K, 2 at 512K). An explicit none is still refused for such a context, with the reason and the way out spelled out instead of a bare stop; explicit linear/yarn/scale pass verbatim; inside the trained 262144 nothing turns on by itself. The resolution moved AFTER the RAM reduction (the §4 ordering): the factor must cover the context the engine will serve, so a 384K choice reduced to 128K by the RAM limit gets no scaling at all, and an explicit selection that survives the reduction says so in a warning. The rope config is now two pure functions (covering_factor, resolve_rope) with its own unit tests (tools/test_setup_rope.py); the engine args take the resolved values; help, module docstring, the context menu note, README and docs/DETAILS.md describe the implemented behavior. --- README.md | 4 +- docs/DETAILS.md | 10 ++-- setup.py | 99 +++++++++++++++++++++++++++++----------- tools/test_setup_rope.py | 84 ++++++++++++++++++++++++++++++++++ 4 files changed, 164 insertions(+), 33 deletions(-) create mode 100644 tools/test_setup_rope.py diff --git a/README.md b/README.md index d72bb816..5df47299 100644 --- a/README.md +++ b/README.md @@ -103,8 +103,8 @@ App). Everything else - Python, the engine, the model - is set up for you. 3. Answer a few questions - or just press Enter each time for the recommended choice: - **Which model and size?** The original or Swift 1.5, and Q2_0, IQ2_XS, IQ3_XXS or IQ3_S - see [above](#which-model-should-i-pick) - **How much context?** How much text it can keep in mind at once (it suggests one for your card). 384K and - 512K extend the model past its trained 262K by rope scaling - the setup adds the flag itself - ([details](docs/DETAILS.md)) + 512K extend the model past its trained 262K by rope scaling - the setup turns it on itself (yarn and a + covering factor; `--rope-scaling`/`--rope-scale` override) ([details](docs/DETAILS.md)) - **Images?** Whether it should also read pictures - **Experimental speed projection?** Off unless you say yes - [read what it does](docs/DETAILS.md#experimental-speed-projection-experimental-off-by-default) first diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 429dbbd3..af63b963 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -435,9 +435,11 @@ high-frequency angles and interpolates the low-frequency ones, with the magnitud the attention temperature where training put it. Scaled contexts also need proportionally more VRAM/RAM for the KV cache and the rope tables (~13 KB and ~0.26 KB per token). -- setup: `START-HERE.bat --setup --context 393216` asks nothing extra - it picks the factor for you - (`--rope-scale` overrides; 393K wants 1.5, 524K wants 2). Contexts past 262,144 refuse to start without - `--rope-scaling`. +- setup: `START-HERE.bat --setup --context 393216` asks nothing extra - it picks the method (yarn; one + question when run interactively) and the smallest covering factor for you (`--rope-scaling`/`--rope-scale` + override; 393K wants 1.5, 524K wants 2). An explicit `--rope-scaling none` for a context past 262,144 is + refused: the setup will not configure a run with the stock angles past the trained range. If the RAM check + reduces a chosen 384K/512K back inside the trained range, no scaling is added at all. - engine: `--rope-scaling none|linear|yarn`, `--rope-scale F`, and the raw ggml knobs `--rope-freq-base`, `--rope-freq-scale`, `--yarn-orig-ctx` (default 262,144), `--yarn-ext-factor`, `--yarn-attn-factor`, `--yarn-beta-fast` (32), `--yarn-beta-slow` (1). The model file's `rope.scaling.*` keys, when a @@ -579,7 +581,7 @@ the document, +0.4% on the chat. Details: `bench/results/2026-09-27-esp/`. | `the engine stopped unexpectedly (exit code ...)` | The engine process ended mid-answer - usually out of RAM (Linux ends the biggest program: `sudo dmesg \| grep -i -E 'killed process\|out of memory'`). The next request starts it again by itself. If it repeats: close other programs or pick a smaller size. The server also warns at start when the model's experts leave less than ~6 GB of RAM for everything else. | | Slow output, disk light busy | Not enough free RAM: close other programs, or choose Q2_0 / IQ2_XS. | | `prompt ... exceeds the context` | The request is longer than the context you chose: run setup again with a bigger `--context`. | -| `past the model's trained 262144` (setup) / the engine refuses a context over 262,144 | A context past the trained one needs rope scaling (engine 0.1.18+): pass `--rope-scaling linear` or `yarn`, or let setup pick it (`START-HERE.bat --setup --context 393216`). | +| `the setup refuses --rope-scaling none for a past-trained context` | A context past the trained 262,144 needs the rotary angles rescaled (engine 0.1.18+), and the setup will not configure one with the stock angles there. Let it pick (`START-HERE.bat --setup --context 393216` adds yarn and a covering factor), or pass `--rope-scaling linear` or `yarn` yourself. | | Slower than the tables | The monitor plugged into the GPU and other GPU programs take VRAM from the expert cache; RAM running below its rated speed (enable EXPO/XMP in the BIOS) slows the CPU half. | | `this server was started without the vision encoder` | The model was set up for text only: run setup again with `--vision gpu`. | | A picture is refused or `cannot read the image` | The file is not a picture Pillow can open (JPEG, PNG, WebP, GIF, BMP, TIFF, AVIF work). | diff --git a/setup.py b/setup.py index be4e7032..bca08616 100644 --- a/setup.py +++ b/setup.py @@ -20,7 +20,8 @@ What the first run does (each step is skipped when it is already done): 7. writes run-.bat / run-.sh and starts the model Options: --family qwen|swift, --model Q2_0|IQ2_XS|IQ3_XXS|IQ3_S, --context 32768, --rope-scaling none|linear|yarn -(--rope-scale F, for contexts past the trained 262144), --vision yes|no|gpu|cpu, --port 8080, --yes (recommended +(--rope-scale F; a context past the trained 262144 gets yarn and a covering factor automatically - an explicit +--rope-scaling none is refused for such a context), --vision yes|no|gpu|cpu, --port 8080, --yes (recommended answers, no questions), --setup (install another model / change settings instead of starting), --no-start, --host 0.0.0.0 --api-key KEY (reach it from other devices on your network), --experimental-speed-projection on|off (EXPERIMENTAL, off by default), @@ -78,8 +79,10 @@ MODELS = { "IQ1_M": {"about": "the Coder's only size: half the experts, stored like IQ3_S (3.5 bits)", "download_gb": 58.4, "ram_gb": 32, "arena_gb": 23.4, "families": ("coder",)}, } -# Contexts past 262144 (the model's trained length) extend it by rope scaling - the engine refuses them -# without --rope-scaling, and the setup adds the flag when the chosen context needs it (below). +# Contexts past 262144 (the model's trained length) extend it by rope scaling: for the context it will +# serve the setup resolves the method (yarn, or one question when interactive) and the smallest covering +# factor itself (below), keeps an explicit --rope-scaling/--rope-scale, and refuses an explicit +# --rope-scaling none there - the stock angles past the trained range are out of spec. CONTEXTS = [8192, 32768, 65536, 131072, 262144, 393216, 524288] # The model families: the same architecture, weights in the same three GSQ-RCO sizes, different files. FAMILIES = { @@ -1585,6 +1588,37 @@ def write_run_script(model, cfg_path, port): return script +# ------------------------------------------------------------------------------------------------ the rope config +def covering_factor(ctx: int, trained: int = 262144) -> float: + """The smallest extension factor on the safe side that covers a chosen context.""" + return next(f for f in (1.5, 2.0) if trained * f >= ctx) + + +def resolve_rope(ctx: int, scaling, scale, trained: int = 262144): + """The rope config for the context ACTUALLY SERVED: (scaling, scale); scaling None = no scaling flags. + + An explicit --rope-scaling/--rope-scale always wins. Past the trained range an omitted method + defaults to yarn - llama.cpp's extension method: the trained angles survive on the high-frequency + pairs and the magnitude correction keeps the attention temperature - and an omitted factor to the + smallest that covers the context. Inside the trained range nothing is added unless explicitly asked + for, and an explicit none is refused past the trained range (the setup will not configure a run it + knows is out of spec) rather than silently overridden. + """ + if ctx <= trained: + if scale is not None and scaling in (None, "none"): + raise ValueError("--rope-scale needs --rope-scaling linear or yarn (the chosen context fits the " + "trained 262144, so there is nothing to scale)") + if scaling in (None, "none"): + return None, None # the stock model, by choice or by default + return scaling, scale if scale is not None else 2.0 + if scaling == "none": + raise ValueError(f"a {ctx // 1024}K context is past the model's trained 262144, and --rope-scaling none " + "keeps the stock angles there - the model has never seen those positions, so the setup " + "refuses the combination instead of quietly overriding it. Pick --rope-scaling yarn or " + "linear, or rerun with --context 262144 or lower") + return scaling or "yarn", scale if scale is not None else covering_factor(ctx, trained) + + # ------------------------------------------------------------------------------------------------ main def main() -> int: ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) @@ -1592,10 +1626,12 @@ def main() -> int: ap.add_argument("--model", choices=list(MODELS)) ap.add_argument("--context", type=int) ap.add_argument("--rope-scaling", choices=["none", "linear", "yarn"], - help="extend the context past the model's trained 262144: linear (position interpolation) or " - "yarn, llama.cpp's types; required for --context 393216/524288") - ap.add_argument("--rope-scale", type=float, help="the extension factor for --rope-scaling (default 2 when a " - "scaled context is chosen without one)") + help="the RoPE extension for a context past the model's trained 262144: linear (position " + "interpolation) or yarn - llama.cpp's types. Omitted with a scaled context, the setup " + "picks yarn; 'none' is refused for such a context") + ap.add_argument("--rope-scale", type=float, + help="the extension factor (default: the smallest that covers the chosen context - 1.5 for " + "384K, 2 for 512K)") ap.add_argument("--kv", choices=["int8", "q4_0", "k8v4"], help="KV cache precision above 8K context: int8 (default), q4_0 (half the memory, a little less " "precise) or k8v4 (hybrid: INT8 K + 4-bit V, 816 B/cell)") @@ -1860,32 +1896,41 @@ def main() -> int: say(" Longer needs more VRAM for it, so fewer experts fit on the GPU:") for i, c in enumerate(CONTEXTS, 1): note = (" (recommended for your GPU)" if c == rec_ctx else "") + \ - (" (needs rope scaling)" if c > 262144 else "") + (" (setup adds rope scaling)" if c > 262144 else "") say(f" {i}) {c // 1024}K tokens{note}") ctx = CONTEXTS[int(ask("Context?", [str(i) for i in range(1, len(CONTEXTS) + 1)], str(CONTEXTS.index(rec_ctx) + 1), a.yes)) - 1] - if ctx > 262144 and a.rope_scaling in (None, "none"): - fail(f"a {ctx // 1024}K context is past the model's trained 262144: pass --rope-scaling linear or yarn " - "(the engine scales the rotary angles; see docs/DETAILS.md)") - rope_scale = a.rope_scale - if ctx > 262144 and rope_scale is None: - # the smallest factor that covers the chosen context, on the safe side - rope_scale = 1.5 if ctx <= 393216 else 2.0 - ok(f"rope scaling: factor {rope_scale:g} (covers {ctx // 1024}K; override with --rope-scale)") - elif rope_scale is not None and a.rope_scaling in (None, "none"): - fail("--rope-scale needs --rope-scaling linear or yarn") - if a.rope_scaling not in (None, "none") and rope_scale is None: - rope_scale = 2.0 - ok("rope scaling: factor 2 (override with --rope-scale)") - # The experts' arena plus the context's KV (in RAM from 64K up: ~13.7 KB/token at 8 bits) must fit, with room - # for everything else. Counted, not a fixed 90 GB: 24 GB of room keeps the rule for 64 GB PCs as it was (128K - # for both 3-bit models), while a box with ~84 GB keeps the 262K it asked for (measured: a Colab A100-40G runs - # IQ3_S at 262K with images in 56 of its 83.5 GiB). + # the RAM limit comes FIRST: the rope config must cover the context the engine will actually serve - + # a reduced 384K can land back inside the trained 262144, and then nothing needs scaling (§4). Counted, + # not a fixed 90 GB (the 0.1.29 arithmetic): arena + the context's KV + 24 GB of room for everything else. + asked_ctx = ctx need_gb = MODELS[model].get("arena_gb", 0) + ctx * 13 * 1056 / 1e9 + 24 if model in ("IQ3_XXS", "IQ3_S") and ram < need_gb and ctx > 131072: warn(f"{model} with a {ctx // 1024}K context needs about {need_gb:.0f} GB of RAM " f"({MODELS[model]['arena_gb']:.0f} GB of experts + the context + room for the rest): using 128K") ctx = 131072 + scaling = a.rope_scaling + if ctx > 262144 and scaling is None: + # the automatic path the docs promise: one question when interactive (yarn preselected), the + # silent default with --yes - llama.cpp's extension method, recall-tested here at 512K + say() + say(f" A {ctx // 1024}K context runs the model past its trained 262,144 positions: the rotary angles") + say(" get rescaled (llama.cpp's RoPE extension). yarn keeps the trained angles on the high-frequency") + say(" pairs and corrects the magnitudes; linear shrinks every angle. Override any time with") + say(" --rope-scaling; with --yes the setup takes yarn without asking.") + scaling = ask("RoPE extension method?", ["yarn", "linear"], "yarn", a.yes) + try: + scaling, rope_scale = resolve_rope(ctx, scaling, a.rope_scale) + except ValueError as e: + fail(str(e)) + if scaling is not None: + ok(f"rope scaling: {scaling}, factor {rope_scale:g} (covers {ctx // 1024}K)" + + ("" if a.rope_scale is not None else "; override with --rope-scale")) + elif asked_ctx > 262144: + ok(f"the RAM limit brings the context to {ctx // 1024}K, inside the trained 262,144: no rope scaling") + if scaling is not None and asked_ctx > 262144 and ctx <= 262144: + warn(f"the RAM limit reduced the context to {ctx // 1024}K, inside the trained 262,144; keeping your " + f"explicit rope scaling ({scaling}) anyway - drop --rope-scaling for the completely stock model") ok(f"context: {ctx} tokens") # the KV cache (the model's memory of the conversation): 8-bit, or 4-bit after a Hadamard rotation (PR #21) kv = "fp16" if ctx <= 8192 else (a.kv or "int8") @@ -2050,8 +2095,8 @@ def main() -> int: "--expert-profile", str(ROOT / "data" / fam.get("profile", "expert-profile.bin")), "--expert-cache", "auto", "--prefill", "auto", "--spec", "4", "--spec-min-p", "0.5", "--mtp", str(rt), "--max-context", str(ctx)] - if a.rope_scaling not in (None, "none"): - args += ["--rope-scaling", a.rope_scaling, "--rope-scale", f"{rope_scale:g}"] + if scaling is not None: # the resolved config: explicit flags as given, or the automatic yarn+factor + args += ["--rope-scaling", scaling, "--rope-scale", f"{rope_scale:g}"] if ctx > 8192: args += ["--kv", kv] if low_ram: diff --git a/tools/test_setup_rope.py b/tools/test_setup_rope.py new file mode 100644 index 00000000..3d4d8b11 --- /dev/null +++ b/tools/test_setup_rope.py @@ -0,0 +1,84 @@ +"""Tests for setup.py's automatic rope configuration (the §6 flow): the setup resolves the method and the +factor for a context past the trained 262144, keeps explicit choices, refuses an explicit none there, and +adds nothing inside the trained range. Pure functions - no GPU, no downloads, no prompts. + + python -m unittest tools.test_setup_rope +""" +from __future__ import annotations + +import sys +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +import setup # noqa: E402 + + +class CoveringFactor(unittest.TestCase): + def test_the_menu_contexts(self): + self.assertEqual(setup.covering_factor(393216), 1.5) # 262144 * 1.5 covers 384K exactly + self.assertEqual(setup.covering_factor(524288), 2.0) # 262144 * 2.0 covers 512K exactly + self.assertEqual(setup.covering_factor(262144), 1.5) # the smallest on the safe side + + def test_the_first_gap_takes_the_bigger_factor(self): + self.assertEqual(setup.covering_factor(393217), 2.0) # one token past 1.5's reach + + +class ResolveRope(unittest.TestCase): + # ---- the automatic flow the docs promise (an omitted flag, --yes or the interactive default) + def test_omitted_384k_gets_yarn_and_the_covering_factor(self): + self.assertEqual(setup.resolve_rope(393216, None, None), ("yarn", 1.5)) + + def test_omitted_512k_gets_yarn_and_the_covering_factor(self): + self.assertEqual(setup.resolve_rope(524288, None, None), ("yarn", 2.0)) + + def test_deterministic_for_yes(self): + # --yes never prompts, so the resolution must be a pure function of its inputs + for _ in range(3): + self.assertEqual(setup.resolve_rope(524288, None, None), ("yarn", 2.0)) + + def test_omitted_method_with_an_explicit_factor(self): + # --rope-scale alone still expresses the intent to extend: the method defaults, the factor is kept + self.assertEqual(setup.resolve_rope(393216, None, 1.8), ("yarn", 1.8)) + + # ---- explicit selections are respected + def test_explicit_method_gets_the_covering_factor(self): + self.assertEqual(setup.resolve_rope(524288, "linear", None), ("linear", 2.0)) + + def test_explicit_method_and_factor_are_kept_verbatim(self): + self.assertEqual(setup.resolve_rope(393216, "linear", 2.0), ("linear", 2.0)) + self.assertEqual(setup.resolve_rope(524288, "yarn", 1.5), ("yarn", 1.5)) + + # ---- an explicit none past the trained range is refused with an explanation, not overridden + def test_explicit_none_past_trained_is_refused(self): + with self.assertRaises(ValueError) as cm: + setup.resolve_rope(524288, "none", None) + self.assertIn("262144", str(cm.exception)) + self.assertIn("yarn", str(cm.exception)) # the message names the way out + + def test_explicit_none_within_trained_is_the_stock_model(self): + self.assertEqual(setup.resolve_rope(131072, "none", None), (None, None)) + + # ---- inside the trained range nothing turns on by itself + def test_omitted_within_trained_adds_nothing(self): + self.assertEqual(setup.resolve_rope(262144, None, None), (None, None)) + self.assertEqual(setup.resolve_rope(131072, None, None), (None, None)) + + def test_a_scale_alone_within_trained_is_rejected(self): + with self.assertRaises(ValueError): + setup.resolve_rope(131072, None, 2.0) + + def test_explicit_method_within_trained_keeps_the_engine_default_factor(self): + self.assertEqual(setup.resolve_rope(131072, "yarn", None), ("yarn", 2.0)) + + # ---- §4 coordination: the RAM reduction lands BEFORE the rope config, so a reduced 384K needs nothing + def test_a_reduced_context_resolves_as_the_reduced_one(self): + # asked 393216, the RAM check brought it to 131072: the setup must not scale a trained-range context + self.assertEqual(setup.resolve_rope(131072, None, None), (None, None)) + # ...but an explicit selection survives the reduction (the engine's in-range caveat is its own) + self.assertEqual(setup.resolve_rope(131072, "yarn", None), ("yarn", 2.0)) + + +if __name__ == "__main__": + unittest.main() From 00db760854d6d414d30779999dec79bbf1d79c07 Mon Sep 17 00:00:00 2001 From: Jakub Luwierski Date: Tue, 29 Sep 2026 17:00:45 +0200 Subject: [PATCH 10/18] setup: a free-form --context past the menu got a raw StopIteration The triple-check pass found what the menu could not: --context is not limited to CONTEXTS, and the factor ladder (1.5, 2.0) ended at 512K, so `--context 600000` died with a bare traceback instead of a setup message. The ladder extends (3, 4) and a context past its top refuses cleanly, naming --rope-scale as the way out. The interactive explanation block also stays quiet under --yes, whose ok() line announces the choice already. --- setup.py | 14 +++++++++----- tools/test_setup_rope.py | 8 ++++++++ 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/setup.py b/setup.py index bca08616..d218ee12 100644 --- a/setup.py +++ b/setup.py @@ -1591,7 +1591,11 @@ def write_run_script(model, cfg_path, port): # ------------------------------------------------------------------------------------------------ the rope config def covering_factor(ctx: int, trained: int = 262144) -> float: """The smallest extension factor on the safe side that covers a chosen context.""" - return next(f for f in (1.5, 2.0) if trained * f >= ctx) + for f in (1.5, 2.0, 3.0, 4.0): + if trained * f >= ctx: + return f + raise ValueError(f"a {ctx} token context is {ctx / trained:.1f}x the trained 262144 - past anything this " + "setup picks a factor for: pass --rope-scale explicitly if you know what you are asking for") def resolve_rope(ctx: int, scaling, scale, trained: int = 262144): @@ -1910,14 +1914,14 @@ def main() -> int: f"({MODELS[model]['arena_gb']:.0f} GB of experts + the context + room for the rest): using 128K") ctx = 131072 scaling = a.rope_scaling - if ctx > 262144 and scaling is None: - # the automatic path the docs promise: one question when interactive (yarn preselected), the - # silent default with --yes - llama.cpp's extension method, recall-tested here at 512K + if ctx > 262144 and scaling is None and not a.yes: + # the interactive path: one question, yarn preselected (llama.cpp's extension method, recall-tested + # here at 512K). With --yes nothing prints: resolve_rope takes yarn below and the ok() line says so. say() say(f" A {ctx // 1024}K context runs the model past its trained 262,144 positions: the rotary angles") say(" get rescaled (llama.cpp's RoPE extension). yarn keeps the trained angles on the high-frequency") say(" pairs and corrects the magnitudes; linear shrinks every angle. Override any time with") - say(" --rope-scaling; with --yes the setup takes yarn without asking.") + say(" --rope-scaling.") scaling = ask("RoPE extension method?", ["yarn", "linear"], "yarn", a.yes) try: scaling, rope_scale = resolve_rope(ctx, scaling, a.rope_scale) diff --git a/tools/test_setup_rope.py b/tools/test_setup_rope.py index 3d4d8b11..c81c3fdd 100644 --- a/tools/test_setup_rope.py +++ b/tools/test_setup_rope.py @@ -24,6 +24,14 @@ class CoveringFactor(unittest.TestCase): def test_the_first_gap_takes_the_bigger_factor(self): self.assertEqual(setup.covering_factor(393217), 2.0) # one token past 1.5's reach + def test_a_free_form_context_past_the_menu_gets_the_next_factor(self): + self.assertEqual(setup.covering_factor(600000), 3.0) # --context is not limited to the menu + + def test_a_context_past_the_whole_ladder_is_a_clean_refusal(self): + with self.assertRaises(ValueError) as cm: + setup.covering_factor(1048577) # 262144 * 4 is the last rung + self.assertIn("--rope-scale", str(cm.exception)) + class ResolveRope(unittest.TestCase): # ---- the automatic flow the docs promise (an omitted flag, --yes or the interactive default) From 79926c0d3f0d519f27a1e6fb59848d18479b753a Mon Sep 17 00:00:00 2001 From: Jakub Luwierski Date: Tue, 29 Sep 2026 17:19:59 +0200 Subject: [PATCH 11/18] setup: the automatic rope factor derives from the context actually served The factor ladder (smallest of 1.5/2/3/4 covering the chosen context) is gone. The automatic factor is now the final context over the trained 262144, clamped at 1 - max(1.0, final / trained) - computed AFTER the RAM reductions, so it always matches the context the engine will serve: 512K + IQ3_S under 90 GB of RAM + yarn, no factor: final 128K, factor 1 no reduction: 384K -> 1.5, 512K -> 2 a chosen method inside the trained range: factor 1, not 2 Factor 1 removes the automatic expansion - the trained angles stand - but it is not a switch for rope as a whole: an explicitly chosen method's settings keep their defined behavior. A user-supplied --rope-scale is still kept verbatim when a reduction changes the context; the ok() line now says where the factor came from (final context / trained, or as requested), and help, docstring and docs/DETAILS.md drop the "smallest covering factor" wording. --- docs/DETAILS.md | 11 ++++--- setup.py | 53 ++++++++++++++++-------------- tools/test_setup_rope.py | 69 +++++++++++++++++++++++----------------- 3 files changed, 76 insertions(+), 57 deletions(-) diff --git a/docs/DETAILS.md b/docs/DETAILS.md index af63b963..7f5a8184 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -436,10 +436,13 @@ the attention temperature where training put it. Scaled contexts also need propo for the KV cache and the rope tables (~13 KB and ~0.26 KB per token). - setup: `START-HERE.bat --setup --context 393216` asks nothing extra - it picks the method (yarn; one - question when run interactively) and the smallest covering factor for you (`--rope-scaling`/`--rope-scale` - override; 393K wants 1.5, 524K wants 2). An explicit `--rope-scaling none` for a context past 262,144 is - refused: the setup will not configure a run with the stock angles past the trained range. If the RAM check - reduces a chosen 384K/512K back inside the trained range, no scaling is added at all. + question when run interactively) and derives the factor from the final context for you (final context / + 262,144, at least 1: 1.5 at 393K, 2 at 512K, 1 inside the trained range; `--rope-scaling`/`--rope-scale` + override, an explicit factor is kept as given). An explicit `--rope-scaling none` for a context past + 262,144 is refused: the setup will not configure a run with the stock angles past the trained range. If + the RAM check reduces a chosen 384K/512K back inside the trained range, an omitted method adds no + scaling, and an explicitly chosen one stays at factor 1 - the trained angles, no expansion (not a + switch for rope as a whole: explicitly supplied rope settings keep their behavior). - engine: `--rope-scaling none|linear|yarn`, `--rope-scale F`, and the raw ggml knobs `--rope-freq-base`, `--rope-freq-scale`, `--yarn-orig-ctx` (default 262,144), `--yarn-ext-factor`, `--yarn-attn-factor`, `--yarn-beta-fast` (32), `--yarn-beta-slow` (1). The model file's `rope.scaling.*` keys, when a diff --git a/setup.py b/setup.py index d218ee12..0293d6b2 100644 --- a/setup.py +++ b/setup.py @@ -20,8 +20,9 @@ What the first run does (each step is skipped when it is already done): 7. writes run-.bat / run-.sh and starts the model Options: --family qwen|swift, --model Q2_0|IQ2_XS|IQ3_XXS|IQ3_S, --context 32768, --rope-scaling none|linear|yarn -(--rope-scale F; a context past the trained 262144 gets yarn and a covering factor automatically - an explicit ---rope-scaling none is refused for such a context), --vision yes|no|gpu|cpu, --port 8080, --yes (recommended +(--rope-scale F; past the trained 262144 the setup adds yarn and the factor is the final context over 262144, +at least 1 - an explicit --rope-scaling none is refused for such a context), --vision yes|no|gpu|cpu, --port +8080, --yes (recommended answers, no questions), --setup (install another model / change settings instead of starting), --no-start, --host 0.0.0.0 --api-key KEY (reach it from other devices on your network), --experimental-speed-projection on|off (EXPERIMENTAL, off by default), @@ -80,9 +81,10 @@ MODELS = { "ram_gb": 32, "arena_gb": 23.4, "families": ("coder",)}, } # Contexts past 262144 (the model's trained length) extend it by rope scaling: for the context it will -# serve the setup resolves the method (yarn, or one question when interactive) and the smallest covering -# factor itself (below), keeps an explicit --rope-scaling/--rope-scale, and refuses an explicit -# --rope-scaling none there - the stock angles past the trained range are out of spec. +# serve the setup resolves the method (yarn, or one question when interactive) and derives the factor +# from the final context (final / 262144, at least 1) itself (below), keeps an explicit +# --rope-scaling/--rope-scale, and refuses an explicit --rope-scaling none there - the stock angles past +# the trained range are out of spec. CONTEXTS = [8192, 32768, 65536, 131072, 262144, 393216, 524288] # The model families: the same architecture, weights in the same three GSQ-RCO sizes, different files. FAMILIES = { @@ -1589,24 +1591,26 @@ def write_run_script(model, cfg_path, port): # ------------------------------------------------------------------------------------------------ the rope config -def covering_factor(ctx: int, trained: int = 262144) -> float: - """The smallest extension factor on the safe side that covers a chosen context.""" - for f in (1.5, 2.0, 3.0, 4.0): - if trained * f >= ctx: - return f - raise ValueError(f"a {ctx} token context is {ctx / trained:.1f}x the trained 262144 - past anything this " - "setup picks a factor for: pass --rope-scale explicitly if you know what you are asking for") +def derived_factor(ctx: int, trained: int = 262144) -> float: + """The automatic extension factor: the FINAL context over the trained one, at least 1. + + Factor 1 removes the automatic expansion - the trained angles stand as they are - but it is not a + switch for rope as a whole: an explicitly chosen method's settings keep their defined behavior. + """ + return max(1.0, float(ctx) / float(trained)) def resolve_rope(ctx: int, scaling, scale, trained: int = 262144): """The rope config for the context ACTUALLY SERVED: (scaling, scale); scaling None = no scaling flags. - An explicit --rope-scaling/--rope-scale always wins. Past the trained range an omitted method - defaults to yarn - llama.cpp's extension method: the trained angles survive on the high-frequency - pairs and the magnitude correction keeps the attention temperature - and an omitted factor to the - smallest that covers the context. Inside the trained range nothing is added unless explicitly asked - for, and an explicit none is refused past the trained range (the setup will not configure a run it - knows is out of spec) rather than silently overridden. + An explicit --rope-scaling/--rope-scale always wins - a user-supplied factor is kept verbatim even + when a reduction changed the context. Past the trained range an omitted method defaults to yarn - + llama.cpp's extension method: the trained angles survive on the high-frequency pairs and the + magnitude correction keeps the attention temperature - and an omitted factor is derived from the + final context (final / trained, at least 1), as is an explicitly chosen method's missing factor + inside the trained range: factor 1, the trained angles, no expansion. An explicit none is refused + past the trained range (the setup will not configure a run it knows is out of spec) rather than + silently overridden. """ if ctx <= trained: if scale is not None and scaling in (None, "none"): @@ -1614,13 +1618,13 @@ def resolve_rope(ctx: int, scaling, scale, trained: int = 262144): "trained 262144, so there is nothing to scale)") if scaling in (None, "none"): return None, None # the stock model, by choice or by default - return scaling, scale if scale is not None else 2.0 + return scaling, scale if scale is not None else derived_factor(ctx, trained) if scaling == "none": raise ValueError(f"a {ctx // 1024}K context is past the model's trained 262144, and --rope-scaling none " "keeps the stock angles there - the model has never seen those positions, so the setup " "refuses the combination instead of quietly overriding it. Pick --rope-scaling yarn or " "linear, or rerun with --context 262144 or lower") - return scaling or "yarn", scale if scale is not None else covering_factor(ctx, trained) + return scaling or "yarn", scale if scale is not None else derived_factor(ctx, trained) # ------------------------------------------------------------------------------------------------ main @@ -1634,8 +1638,8 @@ def main() -> int: "interpolation) or yarn - llama.cpp's types. Omitted with a scaled context, the setup " "picks yarn; 'none' is refused for such a context") ap.add_argument("--rope-scale", type=float, - help="the extension factor (default: the smallest that covers the chosen context - 1.5 for " - "384K, 2 for 512K)") + help="the extension factor (default: the final context over the trained 262144, at least 1 - " + "1.5 for 384K, 2 for 512K, 1 inside the trained range)") ap.add_argument("--kv", choices=["int8", "q4_0", "k8v4"], help="KV cache precision above 8K context: int8 (default), q4_0 (half the memory, a little less " "precise) or k8v4 (hybrid: INT8 K + 4-bit V, 816 B/cell)") @@ -1928,8 +1932,9 @@ def main() -> int: except ValueError as e: fail(str(e)) if scaling is not None: - ok(f"rope scaling: {scaling}, factor {rope_scale:g} (covers {ctx // 1024}K)" - + ("" if a.rope_scale is not None else "; override with --rope-scale")) + origin = ("final context / trained 262144; override with --rope-scale" if a.rope_scale is None + else "as requested") + ok(f"rope scaling: {scaling}, factor {rope_scale:g} ({origin})") elif asked_ctx > 262144: ok(f"the RAM limit brings the context to {ctx // 1024}K, inside the trained 262,144: no rope scaling") if scaling is not None and asked_ctx > 262144 and ctx <= 262144: diff --git a/tools/test_setup_rope.py b/tools/test_setup_rope.py index c81c3fdd..8e90f528 100644 --- a/tools/test_setup_rope.py +++ b/tools/test_setup_rope.py @@ -1,6 +1,7 @@ -"""Tests for setup.py's automatic rope configuration (the §6 flow): the setup resolves the method and the -factor for a context past the trained 262144, keeps explicit choices, refuses an explicit none there, and -adds nothing inside the trained range. Pure functions - no GPU, no downloads, no prompts. +"""Tests for setup.py's automatic rope configuration (§4 + §6): the factor derives from the FINAL context +actually served - RAM reductions first, then final / trained 262144 clamped at 1 - explicit +--rope-scaling/--rope-scale choices win verbatim, an explicit none is refused past the trained range, and +nothing turns on by itself inside it. Pure functions - no GPU, no downloads, no prompts. python -m unittest tools.test_setup_rope """ @@ -15,30 +16,30 @@ sys.path.insert(0, str(ROOT)) import setup # noqa: E402 -class CoveringFactor(unittest.TestCase): - def test_the_menu_contexts(self): - self.assertEqual(setup.covering_factor(393216), 1.5) # 262144 * 1.5 covers 384K exactly - self.assertEqual(setup.covering_factor(524288), 2.0) # 262144 * 2.0 covers 512K exactly - self.assertEqual(setup.covering_factor(262144), 1.5) # the smallest on the safe side +class DerivedFactor(unittest.TestCase): + """The formula itself: max(1.0, final / trained).""" - def test_the_first_gap_takes_the_bigger_factor(self): - self.assertEqual(setup.covering_factor(393217), 2.0) # one token past 1.5's reach + def test_the_task_table(self): + self.assertEqual(setup.derived_factor(131072), 1.0) # below the trained range: clamped at 1 + self.assertEqual(setup.derived_factor(262144), 1.0) # exactly the trained range: 1 + self.assertEqual(setup.derived_factor(393216), 1.5) # 384K + self.assertEqual(setup.derived_factor(524288), 2.0) # 512K - def test_a_free_form_context_past_the_menu_gets_the_next_factor(self): - self.assertEqual(setup.covering_factor(600000), 3.0) # --context is not limited to the menu + def test_free_form_contexts_get_the_exact_ratio(self): + # /262144 = /2**18 is exact in binary floating point, so no dust + self.assertEqual(setup.derived_factor(600000), 600000 / 262144) + self.assertGreater(setup.derived_factor(600000), 2.0) - def test_a_context_past_the_whole_ladder_is_a_clean_refusal(self): - with self.assertRaises(ValueError) as cm: - setup.covering_factor(1048577) # 262144 * 4 is the last rung - self.assertIn("--rope-scale", str(cm.exception)) + def test_the_clamp_is_what_keeps_128k_at_one(self): + self.assertEqual(setup.derived_factor(131072), 1.0) # NOT the raw 0.5 class ResolveRope(unittest.TestCase): # ---- the automatic flow the docs promise (an omitted flag, --yes or the interactive default) - def test_omitted_384k_gets_yarn_and_the_covering_factor(self): + def test_omitted_384k_gets_yarn_and_1_5(self): self.assertEqual(setup.resolve_rope(393216, None, None), ("yarn", 1.5)) - def test_omitted_512k_gets_yarn_and_the_covering_factor(self): + def test_omitted_512k_gets_yarn_and_2(self): self.assertEqual(setup.resolve_rope(524288, None, None), ("yarn", 2.0)) def test_deterministic_for_yes(self): @@ -50,14 +51,19 @@ class ResolveRope(unittest.TestCase): # --rope-scale alone still expresses the intent to extend: the method defaults, the factor is kept self.assertEqual(setup.resolve_rope(393216, None, 1.8), ("yarn", 1.8)) - # ---- explicit selections are respected - def test_explicit_method_gets_the_covering_factor(self): + # ---- explicit selections are respected, verbatim + def test_explicit_method_gets_the_derived_factor(self): self.assertEqual(setup.resolve_rope(524288, "linear", None), ("linear", 2.0)) def test_explicit_method_and_factor_are_kept_verbatim(self): self.assertEqual(setup.resolve_rope(393216, "linear", 2.0), ("linear", 2.0)) self.assertEqual(setup.resolve_rope(524288, "yarn", 1.5), ("yarn", 1.5)) + def test_an_explicit_override_survives_a_context_reduction(self): + # §4: the RAM check reduced the final context to 128K - a user-supplied factor is NOT recalculated + self.assertEqual(setup.resolve_rope(131072, "yarn", 2.0), ("yarn", 2.0)) + self.assertEqual(setup.resolve_rope(131072, "linear", 1.75), ("linear", 1.75)) + # ---- an explicit none past the trained range is refused with an explanation, not overridden def test_explicit_none_past_trained_is_refused(self): with self.assertRaises(ValueError) as cm: @@ -68,7 +74,7 @@ class ResolveRope(unittest.TestCase): def test_explicit_none_within_trained_is_the_stock_model(self): self.assertEqual(setup.resolve_rope(131072, "none", None), (None, None)) - # ---- inside the trained range nothing turns on by itself + # ---- inside the trained range nothing turns on by itself; a chosen method gets factor 1 def test_omitted_within_trained_adds_nothing(self): self.assertEqual(setup.resolve_rope(262144, None, None), (None, None)) self.assertEqual(setup.resolve_rope(131072, None, None), (None, None)) @@ -77,15 +83,20 @@ class ResolveRope(unittest.TestCase): with self.assertRaises(ValueError): setup.resolve_rope(131072, None, 2.0) - def test_explicit_method_within_trained_keeps_the_engine_default_factor(self): - self.assertEqual(setup.resolve_rope(131072, "yarn", None), ("yarn", 2.0)) + def test_a_chosen_method_within_trained_gets_factor_1(self): + # no more unconditional factor 2: 1 = the trained angles, no automatic expansion + self.assertEqual(setup.resolve_rope(131072, "yarn", None), ("yarn", 1.0)) + self.assertEqual(setup.resolve_rope(262144, "linear", None), ("linear", 1.0)) - # ---- §4 coordination: the RAM reduction lands BEFORE the rope config, so a reduced 384K needs nothing - def test_a_reduced_context_resolves_as_the_reduced_one(self): - # asked 393216, the RAM check brought it to 131072: the setup must not scale a trained-range context - self.assertEqual(setup.resolve_rope(131072, None, None), (None, None)) - # ...but an explicit selection survives the reduction (the engine's in-range caveat is its own) - self.assertEqual(setup.resolve_rope(131072, "yarn", None), ("yarn", 2.0)) + # ---- §4 coordination: the RAM reduction lands BEFORE the rope config, so the factor matches the + # context actually served - the 512K-on-IQ3_S-with-under-90-GB case from the task, end to end + def test_512k_on_a_small_ram_machine_resolves_to_128k_factor_1(self): + # asked 524288 with --rope-scaling yarn and no factor; the RAM check brings the final context to 131072 + self.assertEqual(setup.resolve_rope(131072, "yarn", None), ("yarn", 1.0)) + + def test_no_reduction_384k_and_512k_resolve_as_documented(self): + self.assertEqual(setup.resolve_rope(393216, "yarn", None), ("yarn", 1.5)) + self.assertEqual(setup.resolve_rope(524288, "yarn", None), ("yarn", 2.0)) if __name__ == "__main__": From 29f3aec04dd1e84c1510771016234ca9a9dd83d2 Mon Sep 17 00:00:00 2001 From: Jakub Luwierski Date: Tue, 29 Sep 2026 17:33:47 +0200 Subject: [PATCH 12/18] =?UTF-8?q?test:=20pin=20the=20short-context=20rope?= =?UTF-8?q?=20table=20(=C2=A74,=20no=20factor-2=20fallback=20in=20the=20wi?= =?UTF-8?q?ndow)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The implementation landed with the derived-factor change; per the item's own scope note this is verification and tests, not a second one. The table from the item is now pinned case by case - 131072 and 262144 with yarn and no factor resolve to 1, an explicit --rope-scale 2 stays 2 inside the window, 393216/524288 keep 1.5/2 - and linear is checked under the same rule the old fallback applied to it too. On the real engine the resolved combo runs as "rope scaling yarn, factor 1 (freq_scale 1, mscale 1.000000)" and a greedy 12-token run is token-identical to the stock baseline - evidence on one path, not a bit-identity claim. --- tools/test_setup_rope.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/tools/test_setup_rope.py b/tools/test_setup_rope.py index 8e90f528..85b47f98 100644 --- a/tools/test_setup_rope.py +++ b/tools/test_setup_rope.py @@ -98,6 +98,24 @@ class ResolveRope(unittest.TestCase): self.assertEqual(setup.resolve_rope(393216, "yarn", None), ("yarn", 1.5)) self.assertEqual(setup.resolve_rope(524288, "yarn", None), ("yarn", 2.0)) + # ---- the short-context item's own table: no factor-2 fallback inside the trained window, for either + # method, with the explicit override column kept verbatim + def test_the_short_context_table(self): + cases = [ + (131072, None, "yarn", 1.0), # --context 131072 --rope-scaling yarn + (262144, None, "yarn", 1.0), # --context 262144 --rope-scaling yarn + (393216, None, "yarn", 1.5), + (524288, None, "yarn", 2.0), + (131072, 2.0, "yarn", 2.0), # --rope-scale 2 is kept inside the window + ] + for ctx, scale, method, want in cases: + self.assertEqual(setup.resolve_rope(ctx, method, scale), (method, want), f"ctx {ctx}") + + def test_linear_gets_the_same_rule_as_yarn(self): + # the old fallback applied to both methods, so the fix must too + self.assertEqual(setup.resolve_rope(131072, "linear", None), ("linear", 1.0)) + self.assertEqual(setup.resolve_rope(393216, "linear", None), ("linear", 1.5)) + if __name__ == "__main__": unittest.main() From f8c45322b3976cfe844d97c4fed4a78eba099d6a Mon Sep 17 00:00:00 2001 From: Jakub Luwierski Date: Tue, 29 Sep 2026 18:29:08 +0200 Subject: [PATCH 13/18] test: the indexer batch-vs-sequential parity covers linear and compares bits Item 8 verification. The parity section now runs all three scaling configs - none, linear 2 (angle shrink only), yarn 2 (ramp + mscale) - and "bit-identical" is asserted on the BIT representations (memcmp of the state words), not float !=, which would pass a NaN-payload or -0.0 flip. Each scaled variant must also differ from the none baseline in pooled-key bits, so the parity cannot pass because both sides ignore the scaling. Green on this tree: 0 of 33409 state words differ in every config; 128 (linear) and 192 (yarn) pooled words move. --- src/kernels/qsa_parity.cpp | 43 +++++++++++++++++++++++--------------- 1 file changed, 26 insertions(+), 17 deletions(-) diff --git a/src/kernels/qsa_parity.cpp b/src/kernels/qsa_parity.cpp index 50558362..98495c44 100644 --- a/src/kernels/qsa_parity.cpp +++ b/src/kernels/qsa_parity.cpp @@ -1381,16 +1381,23 @@ int main(int argc, char** argv) { // The prefill path appends a chunk in one native_qsa_indexer_append_batch call, the decode path appends // token by token - and one cache must never be able to tell which path filled it (rope_scaling.hpp's // one-rotation rule). So the batch's whole end state must be BIT-IDENTICAL to the sequential appends', - // under the two extremes of the scaling config: none (today's rotation) and yarn factor 2, whose mscale - // and corr-dims both kernels must take from the same RopeScaling. Eight cells: exactly two completed + // under all three scaling configs: none (today's rotation), linear 2 (pure angle shrink, no correction) + // and yarn 2 (corr-dims ramp and the mscale magnitude) - both kernels must take the same RopeScaling. + // "Bit-identical" is asserted on the bit representations (memcmp of the state words): float != would + // pass a NaN-payload or -0.0 flip that the claim does not cover. Eight cells: exactly two completed // blocks, so the paths' end states agree on block_pos too (a mid-block chunk end leaves the sequential // path pointing at the open block's base and the batch at the last completed one's - upstream C-2's own - // semantics, the same for every scaling). + // semantics, the same for every scaling; see native_qsa_indexer.hpp's block_pos contract). { std::printf("\n-- the native indexer's batched append vs the sequential one\n"); const int64_t NB = 8; // exactly two complete blocks of r=4 const int32_t BASE = 100; // positions 100..107, not cell indices 0..7 const int64_t MC = 1024; // the capacity both sides validate against + using RST = strata::kernels::RopeScalingType; + struct Variant { const char* name; RST type; double factor; double ext; }; + const Variant variants[] = {{"none", RST::None, 1.0, 0.0}, + {"linear 2", RST::Linear, 2.0, 0.0}, + {"yarn 2", RST::YaRN, 2.0, 1.0}}; std::vector raws((size_t) NB * IDXD); for (int64_t t = 0; t < NB; ++t) for (int64_t d = 0; d < IDXD; ++d) @@ -1398,9 +1405,11 @@ int main(int argc, char** argv) { cudaStream_t cs = nullptr; check(cudaStreamCreate(&cs), "cs"); std::vector none_pooled; - for (int variant = 0; variant < 2; ++variant) { + for (const Variant& var : variants) { strata::kernels::RopeScaling sc; - if (variant == 1) { sc.type = strata::kernels::RopeScalingType::YaRN; sc.factor = 2.0; sc.ext_factor = 1.0; } + sc.type = var.type; + sc.factor = var.factor; + sc.ext_factor = var.ext; const size_t prows = (size_t) (MC / R + 1) * IDXD, trows = (size_t) (R - 1) * IDXD; Dev pooledA(prows), deadA(IDXD), tailA(trows), pooledB(prows), deadB(IDXD), tailB(trows); Dev bposA(1), bposB(1), dpos(1); @@ -1425,21 +1434,21 @@ int main(int argc, char** argv) { const std::vector ta = tailA.get(trows), tbb = tailB.get(trows); const std::vector ba = bposA.get(1), bb = bposB.get(1); long long bad = 0; - for (size_t i = 0; i < pa.size(); ++i) bad += pa[i] != pb[i]; - for (size_t i = 0; i < da.size(); ++i) bad += da[i] != db[i]; - for (size_t i = 0; i < ta.size(); ++i) bad += ta[i] != tbb[i]; - bad += ba[0] != bb[0]; - std::printf(" %-44s %s (%lld of %zu state values differ)\n", - variant == 0 ? "batch vs sequential, none" : "batch vs sequential, yarn 2", + for (size_t i = 0; i < pa.size(); ++i) bad += std::memcmp(&pa[i], &pb[i], 4) != 0; + for (size_t i = 0; i < da.size(); ++i) bad += std::memcmp(&da[i], &db[i], 4) != 0; + for (size_t i = 0; i < ta.size(); ++i) bad += std::memcmp(&ta[i], &tbb[i], 4) != 0; + bad += std::memcmp(&ba[0], &bb[0], 4) != 0; + std::printf(" %-44s %s (%lld of %zu state words differ)\n", + (std::string("batch vs sequential, ") + var.name).c_str(), bad ? "*** WRONG ***" : "bit-identical", bad, pa.size() + da.size() + ta.size() + 1); if (bad) ++g_bad; - if (variant == 0) none_pooled = pa; + if (var.type == RST::None) none_pooled = pa; else { - int differ = 0; - for (size_t i = 0; i < pa.size(); ++i) differ += pa[i] != none_pooled[i]; - std::printf(" %-44s %d of %zu pooled values moved\n", "the scaling is visible in the batched keys", - differ, pa.size()); - if (!differ) { std::printf(" *** the batched append ignored its scaling ***\n"); ++g_bad; } + int moved = 0; + for (size_t i = 0; i < pa.size(); ++i) moved += std::memcmp(&pa[i], &none_pooled[i], 4) != 0; + std::printf(" %-44s %d of %zu pooled words differ from the none baseline\n", + (std::string("the scaling is visible, ") + var.name).c_str(), moved, pa.size()); + if (!moved) { std::printf(" *** the batched append ignored its scaling ***\n"); ++g_bad; } } } check(cudaStreamDestroy(cs), "csd"); From 8e2f46ca8ca9a497e720b43229b231a6c07c8fd0 Mon Sep 17 00:00:00 2001 From: Jakub Luwierski Date: Wed, 30 Sep 2026 15:19:41 +0200 Subject: [PATCH 14/18] prefill: the draft layer's batched RoPE takes the one rope config v0.1.29's new draft_kv site (the 0.1.26 batched draft prompt pass) kept upstream's float freq_base form through the rebase, which both misses the scaling on the draft K/V and does not compile against the RopeScaling signature the other four sites carry. It passes rope_scaling() now, like the prompt K, Q and indexer-query sites. --- src/prefill/prefill.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index 9d900d1e..9d10b49a 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -803,7 +803,7 @@ bool Prefill::draft_kv(core::MtpDrafter& mtp, const float* R_rows, const int32_t proj(mixed, mixed_h, w_k, Kc, nb, KV, Nn, 0); proj(mixed, mixed_h, w_v, Vc, nb, KV, Nn, 0); rms_rows(Kc, w_kn, nb * g.n_head_kv, g.head_dim, g.head_dim, EPS, m.cs); - rope(Kc, nb, g.n_head_kv, g.head_dim, KV, c0, (float) strata::kernels::qsa_freq_base(), m.cs); + rope(Kc, nb, g.n_head_kv, g.head_dim, KV, c0, strata::kernels::rope_scaling(), m.cs); if (st.kv_q4) { strata::kernels::fwht256_inplace_cuda(Kc, nb * g.n_head_kv, m.cs); strata::kernels::fwht256_inplace_cuda(Vc, nb * g.n_head_kv, m.cs); From a8e56761a6f03020de9db1cd9e7db2650b55e2c7 Mon Sep 17 00:00:00 2001 From: Jakub Luwierski Date: Wed, 30 Sep 2026 16:28:35 +0200 Subject: [PATCH 15/18] generate: the in-window scaling note stops claiming YaRN's magnitude correction (TODO 22) The note fired for every scaled run inside the trained 262144 and its text named YaRN's magnitude correction even for linear, whose resolved mscale is exactly 1. Split in two: the in-window warning now only says that no position needs the extension while the resolved scaling still applies to every angle, and the magnitude explanation became its own note, printed only when YaRN is resolved and its magnitude multiplier differs from 1 (yarn factor 1 inside the window stays quiet; linear never sees it). The main rope scaling line is unchanged, the numbers it prints already carry the resolved mscale. Diagnostics only. Checked on the rebased tree: none prints nothing, linear 2 prints the in-window note without the magnitude line, yarn 2 prints both (mscale 1.069315), yarn factor 1 prints the in-window note only, and yarn 2 past the trained window prints the magnitude note without the in-window one. --- src/program/generate.cpp | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 83310c56..979dd054 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -1509,9 +1509,14 @@ int main(int argc, char** argv) { (long long) o.max_context, rope_cfg.orig_ctx); if ((double) o.max_context <= rope_cfg.orig_ctx) std::fprintf(stderr, - "strata generate: note: the context is within the trained %.0f - the angles barely move, " - "but YaRN's magnitude correction applies everywhere\n", + "strata generate: note: the context is within the trained %.0f - no position needs the " + "extension, and the resolved scaling still applies to every angle\n", rope_cfg.orig_ctx); + if (rope_cfg.type == RST::YaRN && rope_cfg.mscale() != 1.0) + std::fprintf(stderr, + "strata generate: note: YaRN's magnitude correction scales cos and sin by %.6f " + "at every position\n", + rope_cfg.mscale()); } } strata::core::NativeEmbed native_embed; From d4526cf156f1b7df2e5c63b8fb24e982cbdbb6de Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 30 Sep 2026 16:44:48 +0200 Subject: [PATCH 16/18] qsa: the table indexer's spare rotates at position 0 like the native one (TODO 7) indexer_key_append_kernel skipped the rotation at pos 0, which is only an identity while row 0 of the table is (1, 0). Under YaRN row 0 is (mscale, 0), so dead and pooled[0] stayed the only unscaled keys of a scaled cache and disagreed with the native indexer's spare. The rotation at angle 0 reduces to v * cos_tab[pair] on the rotated dims (the sine is 0 in every scaling), so no partner read and no barrier; unscaled it is v * 1.0f, bit for bit the old value. qsa_parity checks the table spare against the unscaled spare times row 0 (bit-exact), pooled[0] == dead, the native spare's factor, and that YaRN's mscale is observable there. --- src/kernels/cuda/qsa.cu | 16 +++++-- src/kernels/qsa_parity.cpp | 94 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 106 insertions(+), 4 deletions(-) diff --git a/src/kernels/cuda/qsa.cu b/src/kernels/cuda/qsa.cu index f783164e..d1338969 100644 --- a/src/kernels/cuda/qsa.cu +++ b/src/kernels/cuda/qsa.cu @@ -184,10 +184,18 @@ __global__ void indexer_key_append_kernel(const float* __restrict__ raw, const i ss = __dadd_rn(ss, __dmul_rn(v, v)); } const double inv = __ddiv_rn(1.0, __dsqrt_rn(ss / (double) idx_dim + (double) eps)); - dead[d] = (float) (p * inv * (double) w_k_norm[d]); - // rope at position 0 is the identity here (cos = 1, sin = 0 exactly), so no rotation is applied and - // the parity test asserts the value is bit-exact - which is what makes skipping it legitimate. - pooled[d] = dead[d]; + float y = (float) (p * inv * (double) w_k_norm[d]); + // The spare rotates at position 0 - ALWAYS row 0 of the table, whatever `pos_base` is, as the native + // indexer's spare does. At angle 0 the sine is exactly 0 in every scaling (sin(0) * mscale), so the + // pair rotation reduces to `v * cos_tab[pair]` with no partner element to read (and no barrier). + // Unscaled, row 0 is exactly (1, 0) and `v * 1.0f` is `v` bit for bit - today's value, which the + // parity test holds bit-exact. Under YaRN row 0 is (mscale, 0): the rotated dims carry the magnitude + // correction exactly like every other pooled row and like the native kernel's spare (the unrotated + // dims pass through, as in the rotation of the completed blocks below). Skipping the rotation here, + // as this kernel once did, left `dead` and `pooled[0]` the only unscaled keys of a scaled cache. + if (d < n_rot) y *= cos_tab[d % (n_rot / 2)]; + dead[d] = y; + pooled[d] = y; } if (slot != r - 1) return; diff --git a/src/kernels/qsa_parity.cpp b/src/kernels/qsa_parity.cpp index 98495c44..55dec2d3 100644 --- a/src/kernels/qsa_parity.cpp +++ b/src/kernels/qsa_parity.cpp @@ -1454,6 +1454,100 @@ int main(int argc, char** argv) { check(cudaStreamDestroy(cs), "csd"); } + // ================= the spare (position 0) under rope scaling: the table indexer vs the native one ========= + // The spare key (`dead`, and `pooled[0]` until the first block completes) rotates at angle 0. Its sine is + // 0 in every scaling, so the rotation is `v * cos_tab[0][pair]`: exactly `v` unscaled (row 0 is (1, 0), the + // bit-exact value section 2 asserts), `v * mscale` under YaRN - the magnitude every other pooled row and + // the native kernel's spare carry. The table kernel used to skip the rotation at position 0, which left + // the spare the one unscaled key of a scaled cache. Asserted per variant: the table spare is BIT-EXACTLY + // the unscaled spare times row 0 on the rotated dims and the unscaled spare past them; `pooled[0]` equals + // `dead`; the native spare carries the same factor (to f32 rounding: its mscale is formed in float); and + // under YaRN the factor is observable (row 0 is not 1). + { + std::printf("\n-- the spare key (position 0) under rope scaling: table indexer vs native indexer\n"); + using RST = strata::kernels::RopeScalingType; + struct Variant { const char* name; RST type; double factor; double ext; }; + const Variant variants[] = {{"none", RST::None, 1.0, 0.0}, + {"linear 2", RST::Linear, 2.0, 0.0}, + {"yarn 2", RST::YaRN, 2.0, 1.0}}; + const int64_t MC = 64, HALF = S.n_rot / 2, NROT = S.n_rot; + std::vector raw0((size_t) IDXD); + for (int64_t d = 0; d < IDXD; ++d) raw0[(size_t) d] = rnd(3.0); + Dev draw0; + draw0.put(raw0); + Dev dpos0(1); + const int32_t zero = 0; + check(cudaMemcpy(dpos0.p, &zero, 4, cudaMemcpyHostToDevice), "pos0"); + cudaStream_t cs = nullptr; + check(cudaStreamCreate(&cs), "cs"); + const size_t prows = (size_t) (MC / R + 1) * IDXD, trows = (size_t) (R - 1) * IDXD; + // one cell at position 0 through either kernel; returns (dead, pooled[0]) + auto spare = [&](bool native, const strata::kernels::RopeScaling& sc, std::vector& dead, + std::vector& pooled0) { + Dev pooled(prows), dd((size_t) IDXD), tail(trows); + Dev bpos(1); + check(cudaMemset(pooled.p, 0, prows * 4), "zero"); + check(cudaMemset(dd.p, 0, (size_t) IDXD * 4), "zero"); + check(cudaMemset(tail.p, 0, trows * 4), "zero"); + check(cudaMemset(bpos.p, 0, 4), "zero"); + strata::kernels::QsaIndexerBuffers bufs{tail.p, dd.p, pooled.p, bpos.p}; + if (native) { + strata::kernels::native_qsa_indexer_append(draw0.p, dpos0.p, 0, dw_kn.p, EPS, bufs, S, MC, sc, cs); + } else { + std::vector tc((size_t) (MC * HALF)), ts(tc.size()); + strata::kernels::build_rope_table((int) NROT, sc, (int) MC, tc.data(), ts.data()); + Dev dc, dsn; + dc.put(tc); + dsn.put(ts); + strata::kernels::indexer_key_append(draw0.p, dpos0.p, 0, dw_kn.p, EPS, bufs, S, dc.p, dsn.p, cs); + } + check(cudaStreamSynchronize(cs), "sync"); + dead = dd.get((size_t) IDXD); + pooled0 = pooled.get((size_t) IDXD); + }; + std::vector t_none, t_none_p, n_none, n_none_p; + for (const Variant& var : variants) { + strata::kernels::RopeScaling sc; + sc.type = var.type; + sc.factor = var.factor; + sc.ext_factor = var.ext; + std::vector row0c((size_t) (MC * HALF)), row0s(row0c.size()); + strata::kernels::build_rope_table((int) NROT, sc, (int) MC, row0c.data(), row0s.data()); + std::vector td, tp, nd, np; + spare(false, sc, td, tp); + spare(true, sc, nd, np); + if (var.type == RST::None) { t_none = td; t_none_p = tp; n_none = nd; n_none_p = np; } + long long tbad = 0, pbad = 0, sin_bad = 0; + double nworst = 0; + for (int64_t i = 0; i < HALF; ++i) sin_bad += row0s[(size_t) i] != 0.0f; + for (int64_t d = 0; d < IDXD; ++d) { + const float c0 = d < NROT ? row0c[(size_t) (d % HALF)] : 1.0f; + const float want = d < NROT ? t_none[(size_t) d] * c0 : t_none[(size_t) d]; + tbad += std::memcmp(&td[(size_t) d], &want, 4) != 0; + pbad += std::memcmp(&tp[(size_t) d], &td[(size_t) d], 4) != 0; + const double nwant = (double) n_none[(size_t) d] * (double) c0; + const double den = std::max(std::fabs(nwant), 1e-6); + nworst = std::max(nworst, std::fabs((double) nd[(size_t) d] - nwant) / den); + } + require(std::string(" ") + var.name + ": row 0 of the table is (c, 0)", sin_bad == 0, + std::to_string(sin_bad) + " nonzero sines"); + require(std::string(" ") + var.name + ": the table spare is the unscaled spare times row 0, BIT-EXACT", + tbad == 0, std::to_string(tbad) + " of " + std::to_string(IDXD) + " wrong"); + require(std::string(" ") + var.name + ": the table's pooled[0] is its spare", pbad == 0, + std::to_string(pbad) + " wrong"); + require(std::string(" ") + var.name + ": the native spare carries the same row-0 factor", nworst <= 4e-7, + "worst relative " + std::to_string(nworst)); + if (var.type == RST::YaRN) { + int moved = 0; + for (int64_t d = 0; d < NROT; ++d) moved += std::memcmp(&td[(size_t) d], &t_none[(size_t) d], 4) != 0; + require(" yarn 2: the magnitude correction is observable on the table spare", + row0c[0] != 1.0f && moved > NROT / 2, + "row0 cos " + std::to_string(row0c[0]) + ", " + std::to_string(moved) + " dims moved"); + } + } + check(cudaStreamDestroy(cs), "csd"); + } + std::printf("\nqsa: %d failures\n", g_bad); if (g_bad) return 1; if (selftest) std::printf("qsa_parity OK\n"); From eb77a8c145a9685cf1d000de974fd8e53412662c Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 30 Sep 2026 16:44:48 +0200 Subject: [PATCH 17/18] rope: one validity rule for the resolved config; none passes the identity constants to every analytic site rope_scaling_invalid() checks every value with std::isfinite first (a NaN passes every range comparison), factor >= 1, original context > 0, a finite positive freq_scale and mscale; the engine applies it to the resolved config (CLI + model file) and fails at startup with the reason, and native_rope, both native indexer appends and the prefill rope use the same rule instead of three hand-copied lists. RopeScaling::kernel_args() gives the analytic kernels their float constants and returns the identity (1, 0, 0, 0, 1) for none whatever the other knobs hold, as the table builder already ignored them: an unscaled run cannot pick up a stray --yarn-attn-factor on the native path only. none resets the knobs (with a note if some were given). The magnitude-correction note prints whenever mscale != 1, and only then (not for plain linear). --- include/strata/kernels/rope_scaling.hpp | 50 +++++++++++++++++++++++++ src/kernels/cuda/native_qsa_indexer.cu | 32 ++++------------ src/kernels/cuda/native_rope.cu | 17 ++------- src/prefill/kernels.cu | 15 ++++---- src/program/generate.cpp | 40 ++++++++++++++++++-- 5 files changed, 104 insertions(+), 50 deletions(-) diff --git a/include/strata/kernels/rope_scaling.hpp b/include/strata/kernels/rope_scaling.hpp index ebb052e2..b494ddc7 100644 --- a/include/strata/kernels/rope_scaling.hpp +++ b/include/strata/kernels/rope_scaling.hpp @@ -47,6 +47,17 @@ namespace strata::kernels { enum class RopeScalingType { None, Linear, YaRN }; +/// The float32 constants the ANALYTIC rotation kernels take (`rope_scaled_angle`'s arguments). The defaults are +/// the identity: freq_scale 1, no correction, magnitude 1 - with them the helper computes `cosf(theta) * 1.0f` +/// on `1.0f * theta`, which is exactly today's unscaled `cosf(theta)` bit for bit. +struct RopeKernelArgs { + float freq_scale = 1.0f; + float corr_low = 0.0f; + float corr_high = 0.0f; + float ext_factor = 0.0f; + float attn_factor = 1.0f; +}; + /// 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 @@ -88,6 +99,23 @@ struct RopeScaling { out[1] = end > (double) (n_rot - 1) ? (double) (n_rot - 1) : end; } + /// The analytic kernels' constants. `none` returns the identity constants WHATEVER the other knobs hold - + /// the table builder ignores them for `none` too, so the two rotation forms cannot disagree there, and an + /// unscaled run computes exactly what it computed before scaling existed. Linear/YaRN: ggml's `rope_yarn` + /// arguments (`attn_factor` is the raw knob; the helper applies the log term when correcting). + RopeKernelArgs kernel_args(int n_rot) const { + RopeKernelArgs a; + if (type == RopeScalingType::None) return a; + double cd[2]; + corr_dims(n_rot, cd); + a.freq_scale = (float) freq_scale(); + a.corr_low = (float) cd[0]; + a.corr_high = (float) cd[1]; + a.ext_factor = (float) ext_factor; + a.attn_factor = (float) attn_factor; + return a; + } + 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))`". @@ -133,6 +161,28 @@ STRATA_ROPE_SCALING_HD inline void rope_scaled_angle(float theta_extrap, float f sin_out = sinf(theta) * mscale; } +/// The ONE validity rule for a resolved configuration, shared by the engine's startup check and every rotation +/// site that takes the struct, so a bad knob cannot pass one site and trip (or silently NaN) another. Returns +/// nullptr when the configuration is usable, else what is wrong. Every value is tested with `std::isfinite` +/// FIRST: a NaN passes every `<`/`<=` range comparison, which is how a `--rope-scale nan` would otherwise slip +/// through. `none` passes with any knob values - the knobs are inert there (the resolution resets them). +inline const char* rope_scaling_invalid(const RopeScaling& s) { + if (!std::isfinite(s.freq_base) || s.freq_base <= 1.0) return "the frequency base must be a finite value above 1"; + if (s.type == RopeScalingType::None) return nullptr; + if (!std::isfinite(s.factor) || s.factor < 1.0) return "the scaling factor must be a finite value >= 1"; + if (!std::isfinite(s.freq_scale_in) || s.freq_scale_in < 0.0) + return "the frequency scale must be finite and positive (0 = 1/factor)"; + const double fs = s.freq_scale(); + if (!std::isfinite(fs) || fs <= 0.0) return "the resolved frequency scale must be a finite positive value"; + if (!std::isfinite(s.orig_ctx) || s.orig_ctx < 1.0) return "the original (trained) context must be finite and > 0"; + if (!std::isfinite(s.ext_factor) || s.ext_factor < 0.0) return "the YaRN ext factor must be finite and >= 0"; + if (!std::isfinite(s.attn_factor) || s.attn_factor <= 0.0) return "the attention factor must be finite and > 0"; + if (!std::isfinite(s.beta_fast) || s.beta_fast <= 0.0 || !std::isfinite(s.beta_slow) || s.beta_slow <= 0.0) + return "the YaRN betas must be finite and > 0"; + if (!std::isfinite(s.mscale()) || s.mscale() <= 0.0) return "the resolved magnitude correction must be finite and > 0"; + return nullptr; +} + /// 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 diff --git a/src/kernels/cuda/native_qsa_indexer.cu b/src/kernels/cuda/native_qsa_indexer.cu index 86d6ae83..299199a9 100644 --- a/src/kernels/cuda/native_qsa_indexer.cu +++ b/src/kernels/cuda/native_qsa_indexer.cu @@ -216,17 +216,10 @@ bool native_qsa_indexer_enabled() { return enabled.load(std::memory_order_relaxe 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, 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(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) + rope_scaling_invalid(scaling) != nullptr) 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}}; @@ -234,35 +227,24 @@ void native_qsa_indexer_append(const float* raw, const int32_t* relative_pos_dev 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((float) scaling.freq_base, -2.0f / ROT); - double corr[2]; - scaling.corr_dims(ROT, corr); + const RopeKernelArgs k = scaling.kernel_args(ROT); // none: the identity constants 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,(float) fs, - (float) corr[0],(float) corr[1],(float) scaling.ext_factor,(float) scaling.attn_factor,mrope_table()); + b.tail,b.dead,b.pooled,b.block_pos,int(max_cells),theta_scale,k.freq_scale, + k.corr_low,k.corr_high,k.ext_factor,k.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, 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(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) + !std::isfinite(epsilon) || epsilon <= 0.0f || rope_scaling_invalid(scaling) != nullptr) 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 RopeKernelArgs k = scaling.kernel_args(ROT); // none: the identity constants + const float fsf = k.freq_scale, cl = k.corr_low, ch = k.corr_high, ef = k.ext_factor, ms = k.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, diff --git a/src/kernels/cuda/native_rope.cu b/src/kernels/cuda/native_rope.cu index d40c4f6b..46311720 100644 --- a/src/kernels/cuda/native_rope.cu +++ b/src/kernels/cuda/native_rope.cu @@ -76,16 +76,9 @@ void native_rope_set_enabled(bool value) { enabled.store(value, std::memory_orde 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, 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(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 || + rope_scaling_invalid(scaling) != nullptr || 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/scaling and explicit stream"); @@ -98,13 +91,11 @@ void native_rope_apply(const float* x, float* out, int rows, int head_dim, } // Match pinned host-side float powf before device fast powf/trigonometry. const float theta_scale = powf((float) scaling.freq_base, -2.0f / n_rot); - double corr[2]; - scaling.corr_dims(n_rot, corr); + const RopeKernelArgs k = scaling.kernel_args(n_rot); // none: the identity constants apply<<(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()); + k.freq_scale, k.corr_low, k.corr_high, k.ext_factor, + k.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 5e74d609..25226735 100644 --- a/src/prefill/kernels.cu +++ b/src/prefill/kernels.cu @@ -763,18 +763,17 @@ void rms_rows(float* x, const float* w, int64_t rows, int64_t cols, int64_t ld, } 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); + // The engine validates the resolved config at startup with the same rule (generate.cpp), so this only + // fires for a caller that bypassed it; the prompt path has no error return here, so it stops the process. + if (const char* why = strata::kernels::rope_scaling_invalid(scaling)) { + std::fprintf(stderr, "prefill rope: invalid rope scaling: %s\n", why); std::exit(1); } const float theta_scale = powf((float) scaling.freq_base, -2.0f / 64.0f); - double corr[2]; - scaling.corr_dims(64, corr); + const strata::kernels::RopeKernelArgs k = scaling.kernel_args(64); // none: the identity constants 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()); + x, heads, dim, ld, pos0, theta_scale, k.freq_scale, k.corr_low, k.corr_high, k.ext_factor, k.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/program/generate.cpp b/src/program/generate.cpp index 979dd054..61d1e855 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -1329,8 +1329,15 @@ int main(int argc, char** argv) { o.rope_scaling.c_str()); return 2; } + // every knob FINITE first: `atof("nan")` is NaN, and a NaN passes every range comparison below + for (const double v : {o.rope_scale, o.rope_freq_base, o.rope_freq_scale, o.yarn_orig_ctx, o.yarn_ext_factor, + o.yarn_attn_factor, o.yarn_beta_fast, o.yarn_beta_slow}) + if (!std::isfinite(v)) { + std::fprintf(stderr, "strata generate: a rope scaling knob is not a finite number (%g)\n", v); + return 2; + } // 0 is the absent default; an explicit factor must extend, not shrink - if (o.rope_scale > 0 && o.rope_scale < 1.0) { + if (o.rope_scale != 0 && o.rope_scale < 1.0) { std::fprintf(stderr, "strata generate: --rope-scale %g must be >= 1 (it extends the context, not shrinks it)\n", o.rope_scale); return 2; @@ -1499,6 +1506,29 @@ int main(int argc, char** argv) { rope_cfg.attn_factor = o.yarn_attn_factor; rope_cfg.beta_fast = o.yarn_beta_fast; rope_cfg.beta_slow = o.yarn_beta_slow; + if (rope_cfg.type == RST::None) { + // none is the trained rotation, exactly: the scaling knobs are inert (the table builder and + // `kernel_args` ignore them), and resetting them keeps the logged/queried config honest. Only the + // frequency base survives - it is the rotation itself, not a scaling knob. + const bool knobs = o.rope_scale > 1.0 || o.rope_freq_scale > 0 || o.yarn_ext_factor > 0 || + o.yarn_attn_factor != 1.0; + const double base = rope_cfg.freq_base; + rope_cfg = strata::kernels::RopeScaling{}; + rope_cfg.freq_base = base; + if (knobs) + std::fprintf(stderr, "strata generate: note: no rope scaling is active (none), so --rope-scale, " + "--rope-freq-scale and the --yarn-* knobs have no effect\n"); + } + // THE RESOLVED CONFIG IS VALIDATED AS A WHOLE, with the one rule every rotation site also applies + // (rope_scaling.hpp): the CLI ranges above cannot see a model-file value, nor a combination such as a + // --rope-freq-scale that turns the resolved factor non-finite. + if (const char* why = strata::kernels::rope_scaling_invalid(rope_cfg)) { + std::fprintf(stderr, "strata generate: invalid rope scaling configuration: %s (type %s, factor %g, " + "freq_scale %g, base %g, original context %g)\n", + why, rope_cfg.type == RST::YaRN ? "yarn" : rope_cfg.type == RST::Linear ? "linear" : "none", + rope_cfg.factor, rope_cfg.freq_scale(), rope_cfg.freq_base, rope_cfg.orig_ctx); + return 2; + } strata::kernels::rope_scaling_set(rope_cfg); if (rope_cfg.type != RST::None) { const char* tn = rope_cfg.type == RST::YaRN ? "yarn" : "linear"; @@ -1512,11 +1542,13 @@ int main(int argc, char** argv) { "strata generate: note: the context is within the trained %.0f - no position needs the " "extension, and the resolved scaling still applies to every angle\n", rope_cfg.orig_ctx); - if (rope_cfg.type == RST::YaRN && rope_cfg.mscale() != 1.0) + // only when there IS a magnitude correction: YaRN's log term (ext_factor != 0) or an explicit + // --yarn-attn-factor; plain linear (mscale 1) has none, and saying otherwise was TODO 22 + if (rope_cfg.mscale() != 1.0) std::fprintf(stderr, - "strata generate: note: YaRN's magnitude correction scales cos and sin by %.6f " + "strata generate: note: the %s magnitude correction scales cos and sin by %.6f " "at every position\n", - rope_cfg.mscale()); + rope_cfg.type == RST::YaRN ? "YaRN" : "--yarn-attn-factor", rope_cfg.mscale()); } } strata::core::NativeEmbed native_embed; From 4240629dba50e3020cbb071c9a48d8503ad5338a Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 30 Sep 2026 16:44:48 +0200 Subject: [PATCH 18/18] docs: rope scaling is experimental and opt-in; the measured perplexity at 293K DETAILS.md: what it does, that no flag means no change, the contributors' paired per-position NLL (yarn 2 -0.18 nats vs none and linear 2 at 293K, no separation at 2.7K/32K, needles not discriminating), the explicit-factor pass-through, fixed per run. The stale 'engine 0.1.18' references go; the setup's 384K/512K menu entries and the README say experimental. --- README.md | 2 +- .../results/2026-09-28-rope-scaling/README.md | 2 +- docs/DETAILS.md | 34 ++++++++++++------- setup.py | 2 +- 4 files changed, 25 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index 5df47299..32490cd8 100644 --- a/README.md +++ b/README.md @@ -103,7 +103,7 @@ App). Everything else - Python, the engine, the model - is set up for you. 3. Answer a few questions - or just press Enter each time for the recommended choice: - **Which model and size?** The original or Swift 1.5, and Q2_0, IQ2_XS, IQ3_XXS or IQ3_S - see [above](#which-model-should-i-pick) - **How much context?** How much text it can keep in mind at once (it suggests one for your card). 384K and - 512K extend the model past its trained 262K by rope scaling - the setup turns it on itself (yarn and a + 512K (experimental) extend the model past its trained 262K by rope scaling - the setup turns it on itself (yarn and a covering factor; `--rope-scaling`/`--rope-scale` override) ([details](docs/DETAILS.md)) - **Images?** Whether it should also read pictures - **Experimental speed projection?** Off unless you say yes - [read what it does](docs/DETAILS.md#experimental-speed-projection-experimental-off-by-default) first diff --git a/bench/results/2026-09-28-rope-scaling/README.md b/bench/results/2026-09-28-rope-scaling/README.md index e1e2e477..1624f43e 100644 --- a/bench/results/2026-09-28-rope-scaling/README.md +++ b/bench/results/2026-09-28-rope-scaling/README.md @@ -1,6 +1,6 @@ # Rope scaling: needle recall past the trained 262K -The feature (engine 0.1.18): `--rope-scaling none|linear|yarn` extends the context past the model's +The feature (PR #84, experimental): `--rope-scaling none|linear|yarn` extends the context past the model's trained 262,144 positions by rescaling the rotary angles - llama.cpp's types, ggml's `rope_yarn` arithmetic, one process config applied at the cos/sin table (default path) and as kernel constants (`--native-rope`, the native indexer, prefill). The three tables here are the first end-to-end check diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 7f5a8184..953810a6 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -428,17 +428,27 @@ it needs, prefer read-only tools, and don't add servers you don't trust. The too page itself (a request with another site's Origin or without a JSON content type is refused); if Strata is reachable from other devices, set an API key. -**Context extension (rope scaling, engine 0.1.18).** The model trains 262,144 positions of rotary base -1e7; the context past that stays coherent by rescaling the rotation angles, with llama.cpp's types and -flag names. `linear` is Position Interpolation (every angle shrunk by the factor); `yarn` keeps the -high-frequency angles and interpolates the low-frequency ones, with the magnitude correction that keeps -the attention temperature where training put it. Scaled contexts also need proportionally more VRAM/RAM -for the KV cache and the rope tables (~13 KB and ~0.26 KB per token). +**Context extension past 262K (rope scaling, EXPERIMENTAL, off unless you pick it).** The model was trained on +262,144 positions (rotary base 1e7). Rope scaling rescales the rotation angles so that longer contexts stay usable, +with llama.cpp's types and flag names. `linear` is Position Interpolation: every angle is shrunk by the factor. +`yarn` keeps the high-frequency angles, interpolates the low-frequency ones, and adds the magnitude correction +that keeps the attention temperature where training put it. **Without the flags nothing changes:** an unscaled +run computes exactly what it did before the feature existed, bit for bit. Scaled contexts need proportionally +more VRAM/RAM for the KV cache and the rope tables (~13 KB and ~0.26 KB per token). + +What was measured (contributors' runs, RTX 5080 + IQ3_S, native path, in PR #84): per-position perplexity on the +same tokens, with only the scaling flag changed. At 293K tokens (1.12x the trained length), `yarn` with factor 2 +lowered the NLL by 0.18 nats against both `none` and `linear` 2 (2.04 vs 2.22 / 2.22). That is 3-4x the path noise +measured at the same length. `linear` 2 was indistinguishable from `none`. At 2.7K and 32K no arm separated from the +noise. Needle tests do not tell the arms apart: the unscaled model also finds a needle at 413K. Long real-document +Q&A worked with `yarn` 2 at 421K and `yarn` 4 at 714K (8/8 each), and a 1M-token `yarn` 4 run read end to end. +Taken together, use **yarn**. It is still experimental: the numbers come from one machine and one quant. - setup: `START-HERE.bat --setup --context 393216` asks nothing extra - it picks the method (yarn; one question when run interactively) and derives the factor from the final context for you (final context / 262,144, at least 1: 1.5 at 393K, 2 at 512K, 1 inside the trained range; `--rope-scaling`/`--rope-scale` - override, an explicit factor is kept as given). An explicit `--rope-scaling none` for a context past + override; an explicit `--rope-scale` is kept as given even when it is too small for the context actually + served, so check it if you set one). An explicit `--rope-scaling none` for a context past 262,144 is refused: the setup will not configure a run with the stock angles past the trained range. If the RAM check reduces a chosen 384K/512K back inside the trained range, an omitted method adds no scaling, and an explicitly chosen one stays at factor 1 - the trained angles, no expansion (not a @@ -450,10 +460,10 @@ for the KV cache and the rope tables (~13 KB and ~0.26 KB per token). The scaling is fixed for the whole run - the engine stores keys in its cache after rotating them, so one cache must never mix two scalings, and there is no per-request form. Within the trained 262,144 a scaled -run is a different (very slightly perturbed) model: `yarn`'s magnitude correction applies everywhere, not -only past the trained end. Needle recall past the trained end passes (262k and 512k prompt probes at -linear 2 and yarn 2, mid-depth, `tools/needle_bench.py`); pictures read the same scaled table (their -(t, h, w) positions feed it), which is expected to compose but unmeasured - the recall runs are text. +run is a slightly different model: the rescaled angles, and `yarn`'s magnitude correction, apply at every +position, not only past the trained end. That is why the setup turns scaling on only for a context past +262,144. Pictures read the same scaled table (their (t, h, w) positions feed it). That should work, but it is +unmeasured: all the runs above are text. --- @@ -584,7 +594,7 @@ the document, +0.4% on the chat. Details: `bench/results/2026-09-27-esp/`. | `the engine stopped unexpectedly (exit code ...)` | The engine process ended mid-answer - usually out of RAM (Linux ends the biggest program: `sudo dmesg \| grep -i -E 'killed process\|out of memory'`). The next request starts it again by itself. If it repeats: close other programs or pick a smaller size. The server also warns at start when the model's experts leave less than ~6 GB of RAM for everything else. | | Slow output, disk light busy | Not enough free RAM: close other programs, or choose Q2_0 / IQ2_XS. | | `prompt ... exceeds the context` | The request is longer than the context you chose: run setup again with a bigger `--context`. | -| `the setup refuses --rope-scaling none for a past-trained context` | A context past the trained 262,144 needs the rotary angles rescaled (engine 0.1.18+), and the setup will not configure one with the stock angles there. Let it pick (`START-HERE.bat --setup --context 393216` adds yarn and a covering factor), or pass `--rope-scaling linear` or `yarn` yourself. | +| `the setup refuses --rope-scaling none for a past-trained context` | A context past the trained 262,144 needs the rotary angles rescaled (experimental rope scaling), and the setup will not configure one with the stock angles there. Let it pick (`START-HERE.bat --setup --context 393216` adds yarn and a covering factor), or pass `--rope-scaling linear` or `yarn` yourself. | | Slower than the tables | The monitor plugged into the GPU and other GPU programs take VRAM from the expert cache; RAM running below its rated speed (enable EXPO/XMP in the BIOS) slows the CPU half. | | `this server was started without the vision encoder` | The model was set up for text only: run setup again with `--vision gpu`. | | A picture is refused or `cannot read the image` | The file is not a picture Pillow can open (JPEG, PNG, WebP, GIF, BMP, TIFF, AVIF work). | diff --git a/setup.py b/setup.py index 0293d6b2..b4458e39 100644 --- a/setup.py +++ b/setup.py @@ -1904,7 +1904,7 @@ def main() -> int: say(" Longer needs more VRAM for it, so fewer experts fit on the GPU:") for i, c in enumerate(CONTEXTS, 1): note = (" (recommended for your GPU)" if c == rec_ctx else "") + \ - (" (setup adds rope scaling)" if c > 262144 else "") + (" (experimental: setup adds rope scaling)" if c > 262144 else "") say(f" {i}) {c // 1024}K tokens{note}") ctx = CONTEXTS[int(ask("Context?", [str(i) for i in range(1, len(CONTEXTS) + 1)], str(CONTEXTS.index(rec_ctx) + 1), a.yes)) - 1]