feat(runtime): port RoPE scaling and cos/sin table builder with Original-derived golden fixtures

Pure Rust (no unsafe) port of rope_scaling.hpp, rope.cu build_rope_table and the
generate.cpp/setup.py knob resolution. Fixtures come from the Original's host code
(verbatim extraction, -ffp-contract=off). Host-side only; CUDA consumption is open.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-10-14 14:42:41 +02:00
co-authored by Claude Sonnet 5.5
parent 8651f784ef
commit c738ab7667
5 changed files with 2282 additions and 0 deletions
+1
View File
@@ -1,6 +1,7 @@
//! Independent Qwen runtime. CUDA state stays inside its dedicated owner thread.
pub mod backend;
pub mod rope_scaling;
pub use backend::spawn_backend_observed_native_integer_iq3_windowed256_retained_gr;
pub use backend::spawn_backend_observed_native_resident_mmq;
+921
View File
@@ -0,0 +1,921 @@
//! RoPE scaling (none / linear / YaRN) and the host-side cos/sin table builder.
//!
//! Literal port of the Original (pinned Strata under `engine/strata/`):
//! - `include/strata/kernels/rope_scaling.hpp` (`RopeScaling`, `rope_yarn_ramp`, `rope_scaled_angle`,
//! `rope_scaling_invalid`, `RopeKernelArgs`),
//! - `src/kernels/cuda/rope.cu` (`build_rope_table`, both overloads),
//! - `src/program/generate.cpp` ~1619-1660 and ~1795-1900 (CLI/model-file knob resolution).
//!
//! The arithmetic order is the Original's, expression by expression: float64 throughout for the table
//! (`inv`, then `ang`, then cos/sin, then one cast to f32), float32 for the ramp and for the analytic path.
//! There is deliberately no fused multiply-add: Rust never contracts, and the golden fixtures are generated
//! with `-ffp-contract=off` (an engine host build that contracts, e.g. aarch64 GCC defaults, can differ in
//! individual YaRN entries; see `docs/rope-and-memory-plan.md`).
//!
//! The only libm-dependent operations are `pow`, `cos`, `sin`, `log` (f64) and `cosf`, `sinf`, `logf` (f32).
//! On macOS Rust and the Original call the same system libm, so the golden comparison is bit-exact; on other
//! libms the tests fall back to a bounded ULP tolerance (see `tests/rope_plan_golden.rs`).
//!
//! Nothing here touches the GPU. Whether the CUDA kernels consume these tables is open.
use std::f64::consts::PI;
use std::fmt;
/// Largest context the charter and `setup.py` (`CONTEXTS`) reach. Builders accept more; policy refuses more.
pub const MAX_CHARTER_CONTEXT: u64 = 524_288;
/// The context the model was trained over (`RopeScaling::orig_ctx` default, `setup.py` `trained`).
pub const TRAINED_CONTEXT: u64 = 262_144;
/// `qsa_freq_base()` in the Original.
pub const DEFAULT_FREQ_BASE: f64 = 1e7;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RopeScalingType {
None,
Linear,
YaRN,
}
impl RopeScalingType {
pub fn name(self) -> &'static str {
match self {
Self::None => "none",
Self::Linear => "linear",
Self::YaRN => "yarn",
}
}
pub fn parse(name: &str) -> Option<Self> {
match name {
"none" => Some(Self::None),
"linear" => Some(Self::Linear),
"yarn" => Some(Self::YaRN),
_ => None,
}
}
}
/// The float32 constants the analytic rotation kernels take. Defaults are the identity.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct RopeKernelArgs {
pub freq_scale: f32,
pub corr_low: f32,
pub corr_high: f32,
pub ext_factor: f32,
pub attn_factor: f32,
}
impl Default for RopeKernelArgs {
fn default() -> Self {
Self {
freq_scale: 1.0,
corr_low: 0.0,
corr_high: 0.0,
ext_factor: 0.0,
attn_factor: 1.0,
}
}
}
/// Why a resolved configuration is unusable. `reason()` is the Original's exact message.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RopeScalingError {
FreqBase,
Factor,
FreqScaleIn,
ResolvedFreqScale,
OrigCtx,
ExtFactor,
AttnFactor,
Betas,
Mscale,
}
impl RopeScalingError {
pub fn reason(self) -> &'static str {
match self {
Self::FreqBase => "the frequency base must be a finite value above 1",
Self::Factor => "the scaling factor must be a finite value >= 1",
Self::FreqScaleIn => "the frequency scale must be finite and positive (0 = 1/factor)",
Self::ResolvedFreqScale => {
"the resolved frequency scale must be a finite positive value"
}
Self::OrigCtx => "the original (trained) context must be finite and > 0",
Self::ExtFactor => "the YaRN ext factor must be finite and >= 0",
Self::AttnFactor => "the attention factor must be finite and > 0",
Self::Betas => "the YaRN betas must be finite and > 0",
Self::Mscale => "the resolved magnitude correction must be finite and > 0",
}
}
}
impl fmt::Display for RopeScalingError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.reason())
}
}
impl std::error::Error for RopeScalingError {}
/// The one rope configuration. `Default` is exactly today's engine: freq_scale 1, mscale 1, no correction.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct RopeScaling {
pub kind: RopeScalingType,
/// `rope.freq_base`.
pub freq_base: f64,
/// `--rope-scale`: how far past the trained context the run goes.
pub factor: f64,
/// `--rope-freq-scale`: the raw ggml knob; 0 = 1/factor.
pub freq_scale_in: f64,
/// `--yarn-orig-ctx`: the context the model was trained over.
pub orig_ctx: f64,
/// `--yarn-ext-factor`: correction depth; 0 = off, 1 = full YaRN.
pub ext_factor: f64,
/// `--yarn-attn-factor`: extra magnitude scale.
pub attn_factor: f64,
pub beta_fast: f64,
pub beta_slow: f64,
}
impl Default for RopeScaling {
fn default() -> Self {
Self {
kind: RopeScalingType::None,
freq_base: DEFAULT_FREQ_BASE,
factor: 1.0,
freq_scale_in: 0.0,
orig_ctx: TRAINED_CONTEXT as f64,
ext_factor: 0.0,
attn_factor: 1.0,
beta_fast: 32.0,
beta_slow: 1.0,
}
}
}
/// ggml `ggml_rope_yarn_corr_dim`, float64 as in the Original.
fn rope_yarn_corr_dim(n_dims: i32, n_ctx_orig: f64, n_rot: f64, base: f64) -> f64 {
f64::from(n_dims) * (n_ctx_orig / (n_rot * 2.0 * PI)).ln() / (2.0 * base.ln())
}
impl RopeScaling {
/// The angle shrink (ggml's `freq_scale`).
pub fn freq_scale(&self) -> f64 {
if self.kind == RopeScalingType::None {
return 1.0;
}
if self.freq_scale_in > 0.0 {
self.freq_scale_in
} else {
1.0 / self.factor
}
}
/// The magnitude correction; the log term rides on `ext_factor != 0`, not on the type.
pub fn mscale(&self) -> f64 {
if self.ext_factor == 0.0 {
return self.attn_factor;
}
self.attn_factor * (1.0 + 0.1 * (1.0 / self.freq_scale()).ln())
}
/// The correction window in PAIR indices, clamped to `[0, n_rot - 1]`.
pub fn corr_dims(&self, n_rot: i32) -> [f64; 2] {
let start =
rope_yarn_corr_dim(n_rot, self.orig_ctx, self.beta_fast, self.freq_base).floor();
let end = rope_yarn_corr_dim(n_rot, self.orig_ctx, self.beta_slow, self.freq_base).ceil();
let hi = f64::from(n_rot - 1);
[
if start < 0.0 { 0.0 } else { start },
if end > hi { hi } else { end },
]
}
/// The analytic kernels' constants; `none` returns the identity whatever the other knobs hold.
pub fn kernel_args(&self, n_rot: i32) -> RopeKernelArgs {
if self.kind == RopeScalingType::None {
return RopeKernelArgs::default();
}
let cd = self.corr_dims(n_rot);
RopeKernelArgs {
freq_scale: self.freq_scale() as f32,
corr_low: cd[0] as f32,
corr_high: cd[1] as f32,
ext_factor: self.ext_factor as f32,
attn_factor: self.attn_factor as f32,
}
}
/// `rope_scaling_invalid`: the one validity rule. Every value is tested with `is_finite` first so a NaN
/// cannot slip through a range comparison.
pub fn validate(&self) -> Result<(), RopeScalingError> {
if !self.freq_base.is_finite() || self.freq_base <= 1.0 {
return Err(RopeScalingError::FreqBase);
}
if self.kind == RopeScalingType::None {
return Ok(());
}
if !self.factor.is_finite() || self.factor < 1.0 {
return Err(RopeScalingError::Factor);
}
if !self.freq_scale_in.is_finite() || self.freq_scale_in < 0.0 {
return Err(RopeScalingError::FreqScaleIn);
}
let fs = self.freq_scale();
if !fs.is_finite() || fs <= 0.0 {
return Err(RopeScalingError::ResolvedFreqScale);
}
if !self.orig_ctx.is_finite() || self.orig_ctx < 1.0 {
return Err(RopeScalingError::OrigCtx);
}
if !self.ext_factor.is_finite() || self.ext_factor < 0.0 {
return Err(RopeScalingError::ExtFactor);
}
if !self.attn_factor.is_finite() || self.attn_factor <= 0.0 {
return Err(RopeScalingError::AttnFactor);
}
if !self.beta_fast.is_finite()
|| self.beta_fast <= 0.0
|| !self.beta_slow.is_finite()
|| self.beta_slow <= 0.0
{
return Err(RopeScalingError::Betas);
}
let ms = self.mscale();
if !ms.is_finite() || ms <= 0.0 {
return Err(RopeScalingError::Mscale);
}
Ok(())
}
}
/// `rope_yarn_ramp`: 1 - clamp(y, 0, 1), float32, taking the PAIR index (ggml's `i0 / 2`).
pub fn rope_yarn_ramp(low: f32, high: f32, pair: i32) -> f32 {
let span = high - low;
let y = (pair as f32 - low) / if span > 0.001 { span } else { 0.001 };
let clamped = y.clamp(0.0, 1.0);
1.0 - clamped
}
/// `rope_scaled_angle`: the analytic paths' float32 contract. Returns `(cos, sin)` with mscale folded in.
pub fn rope_scaled_angle(
theta_extrap: f32,
freq_scale: f32,
corr_low: f32,
corr_high: f32,
ext_factor: f32,
mscale_in: f32,
pair: i32,
) -> (f32, f32) {
let mut theta = freq_scale * theta_extrap;
let mut mscale = mscale_in;
if ext_factor != 0.0 {
let ramp_mix = rope_yarn_ramp(corr_low, corr_high, pair) * ext_factor;
theta = theta * (1.0 - ramp_mix) + theta_extrap * ramp_mix;
mscale *= 1.0 + 0.1 * (1.0 / freq_scale).ln();
}
(theta.cos() * mscale, theta.sin() * mscale)
}
/// Why a table could not be built.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RopeTableError {
Config(RopeScalingError),
/// `n_rot` must be even and non-zero (NEOX pairs) and fit `i32`.
NRot(usize),
/// `n_pos` exceeds the Original's `int max_pos` or the table size overflows.
TooManyPositions(usize),
/// Output slice lengths do not match `rows * n_rot / 2`.
BufferLength,
}
impl fmt::Display for RopeTableError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Config(e) => write!(f, "invalid rope scaling configuration: {e}"),
Self::NRot(n) => write!(f, "n_rot {n} must be even and non-zero"),
Self::TooManyPositions(n) => write!(f, "{n} positions exceed the table limits"),
Self::BufferLength => f.write_str("output buffer length does not match the row count"),
}
}
}
impl std::error::Error for RopeTableError {}
impl From<RopeScalingError> for RopeTableError {
fn from(e: RopeScalingError) -> Self {
Self::Config(e)
}
}
fn check_n_rot(n_rot: usize) -> Result<(), RopeTableError> {
if n_rot == 0 || !n_rot.is_multiple_of(2) || i32::try_from(n_rot).is_err() {
return Err(RopeTableError::NRot(n_rot));
}
Ok(())
}
/// Bytes of the cos plus sin tables (the `with_rope` term in `qsa_state_bytes`).
pub fn rope_table_bytes(n_rot: usize, n_pos: usize) -> Option<u64> {
let half = (n_rot / 2) as u64;
(n_pos as u64).checked_mul(half)?.checked_mul(4 * 2)
}
/// Fill rows `first_pos .. first_pos + rows` of the table into `cos_out` / `sin_out`
/// (`rows * n_rot / 2` entries each, row-major like `cos_tab[p * half + i]`).
///
/// Row `p` depends only on `(n_rot, sc, p)`, so a table of any length is a prefix of any longer one.
/// `RopeScalingType::None` takes the Original's unscaled loop verbatim (no mscale multiply).
pub fn fill_rope_table(
n_rot: usize,
sc: &RopeScaling,
first_pos: usize,
cos_out: &mut [f32],
sin_out: &mut [f32],
) -> Result<(), RopeTableError> {
check_n_rot(n_rot)?;
sc.validate()?;
let half = n_rot / 2;
if cos_out.len() != sin_out.len() || !cos_out.len().is_multiple_of(half) {
return Err(RopeTableError::BufferLength);
}
let rows = cos_out.len() / half;
let end = first_pos
.checked_add(rows)
.ok_or(RopeTableError::TooManyPositions(rows))?;
if i32::try_from(end).is_err() {
return Err(RopeTableError::TooManyPositions(end));
}
// inv[i] depends only on i: hoisting the pow out of the position loop yields the same value per entry.
let n_rot_f = n_rot as f64;
let inv: Vec<f64> = (0..half)
.map(|i| sc.freq_base.powf(-2.0 * (i as f64) / n_rot_f))
.collect();
if sc.kind == RopeScalingType::None {
for r in 0..rows {
let p = (first_pos + r) as f64;
for i in 0..half {
let ang = p * inv[i];
cos_out[r * half + i] = ang.cos() as f32;
sin_out[r * half + i] = ang.sin() as f32;
}
}
return Ok(());
}
let fs = sc.freq_scale();
let ms = sc.mscale();
let cd = sc.corr_dims(n_rot as i32);
let correct = sc.ext_factor != 0.0;
let (low, high) = (cd[0] as f32, cd[1] as f32);
// the ramp depends on the pair only
let ramp: Vec<f64> = (0..half)
.map(|i| f64::from(rope_yarn_ramp(low, high, i as i32)) * sc.ext_factor)
.collect();
for r in 0..rows {
let p = (first_pos + r) as f64;
for i in 0..half {
let extrap = p * inv[i];
let interp = fs * extrap;
let mut ang = interp;
if correct {
ang = interp * (1.0 - ramp[i]) + extrap * ramp[i];
}
cos_out[r * half + i] = (ang.cos() * ms) as f32;
sin_out[r * half + i] = (ang.sin() * ms) as f32;
}
}
Ok(())
}
/// A full `[n_pos][n_rot / 2]` cos/sin table, the layout `build_rope_table` fills and `session_init` uploads.
#[derive(Clone, Debug, PartialEq)]
pub struct RopeTable {
pub n_rot: usize,
pub n_pos: usize,
pub cos: Vec<f32>,
pub sin: Vec<f32>,
}
impl RopeTable {
pub fn half(&self) -> usize {
self.n_rot / 2
}
pub fn row_cos(&self, pos: usize) -> &[f32] {
&self.cos[pos * self.half()..(pos + 1) * self.half()]
}
pub fn row_sin(&self, pos: usize) -> &[f32] {
&self.sin[pos * self.half()..(pos + 1) * self.half()]
}
}
/// `build_rope_table(n_rot, scaling, n_pos, ...)`; `n_pos` up to 524288 (128 MiB for `n_rot` 64) and beyond.
pub fn build_rope_table(
n_rot: usize,
sc: &RopeScaling,
n_pos: usize,
) -> Result<RopeTable, RopeTableError> {
check_n_rot(n_rot)?;
let len = n_pos
.checked_mul(n_rot / 2)
.ok_or(RopeTableError::TooManyPositions(n_pos))?;
let mut cos = vec![0.0f32; len];
let mut sin = vec![0.0f32; len];
fill_rope_table(n_rot, sc, 0, &mut cos, &mut sin)?;
Ok(RopeTable {
n_rot,
n_pos,
cos,
sin,
})
}
// ------------------------------------------------------------------------------------------------
// Knob resolution (generate.cpp): explicit flag over model-file keys over struct defaults.
// ------------------------------------------------------------------------------------------------
/// The CLI knob family. `0` means "flag absent" for the scale/base/orig-ctx/freq-scale knobs, `< 0` for
/// `yarn_ext_factor` (auto: 1 for yarn, 0 otherwise), and `None` for the type, exactly as `Options` in
/// `generate.cpp`.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct RopeKnobs {
pub scaling: Option<RopeScalingType>,
pub rope_scale: f64,
pub rope_freq_base: f64,
pub rope_freq_scale: f64,
pub yarn_orig_ctx: f64,
pub yarn_ext_factor: f64,
pub yarn_attn_factor: f64,
pub yarn_beta_fast: f64,
pub yarn_beta_slow: f64,
}
impl Default for RopeKnobs {
fn default() -> Self {
Self {
scaling: None,
rope_scale: 0.0,
rope_freq_base: 0.0,
rope_freq_scale: 0.0,
yarn_orig_ctx: 0.0,
yarn_ext_factor: -1.0,
yarn_attn_factor: 1.0,
yarn_beta_fast: 32.0,
yarn_beta_slow: 1.0,
}
}
}
/// The model file's rope keys (`qwen4exp.rope.*`); `0` / `None` = absent. The shipped artifact carries none.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ModelRopeKeys {
pub freq_base: f64,
pub scaling_type: Option<String>,
pub factor: f64,
pub orig_ctx: f64,
}
#[derive(Clone, Debug, PartialEq)]
pub enum RopeKnobError {
/// "a rope scaling knob is not a finite number"
NotFinite,
/// "--rope-scale must be >= 1"
ScaleBelowOne,
/// "--rope-freq-base must be a base above 1 (0 = the model's)"
FreqBase,
/// "invalid rope scaling knob"
Knob,
/// the model file carries a `rope.scaling.type` other than none/linear/yarn
ModelType(String),
/// the resolved configuration fails `validate`
Invalid(RopeScalingError),
}
impl fmt::Display for RopeKnobError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::NotFinite => f.write_str("a rope scaling knob is not a finite number"),
Self::ScaleBelowOne => {
f.write_str("--rope-scale must be >= 1 (it extends the context, not shrinks it)")
}
Self::FreqBase => {
f.write_str("--rope-freq-base must be a base above 1 (0 = the model's)")
}
Self::Knob => f.write_str(
"invalid rope scaling knob (--yarn-ext-factor < 0 = auto, --yarn-orig-ctx 0 = default, the rest positive)",
),
Self::ModelType(t) => write!(
f,
"model file carries rope.scaling.type '{t}' - none, linear or yarn only"
),
Self::Invalid(e) => write!(f, "invalid rope scaling configuration: {e}"),
}
}
}
impl std::error::Error for RopeKnobError {}
/// A resolved configuration and whether the `none` branch dropped explicit knobs
/// (the Original prints "no rope scaling is active, so ... have no effect").
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ResolvedRope {
pub scaling: RopeScaling,
pub inert_knobs_ignored: bool,
}
/// Port of the `generate.cpp` rope resolution: range checks, then precedence flag > model file > defaults,
/// the `none` reset, and the whole-config validity rule.
pub fn resolve_rope_scaling(
knobs: &RopeKnobs,
model: &ModelRopeKeys,
) -> Result<ResolvedRope, RopeKnobError> {
let all = [
knobs.rope_scale,
knobs.rope_freq_base,
knobs.rope_freq_scale,
knobs.yarn_orig_ctx,
knobs.yarn_ext_factor,
knobs.yarn_attn_factor,
knobs.yarn_beta_fast,
knobs.yarn_beta_slow,
];
if all.iter().any(|v| !v.is_finite()) {
return Err(RopeKnobError::NotFinite);
}
if knobs.rope_scale != 0.0 && knobs.rope_scale < 1.0 {
return Err(RopeKnobError::ScaleBelowOne);
}
if knobs.rope_freq_base != 0.0 && knobs.rope_freq_base <= 1.0 {
return Err(RopeKnobError::FreqBase);
}
if knobs.rope_freq_scale < 0.0
|| knobs.yarn_orig_ctx < 0.0
|| knobs.yarn_ext_factor < -1.0
|| knobs.yarn_attn_factor <= 0.0
|| knobs.yarn_beta_fast <= 0.0
|| knobs.yarn_beta_slow <= 0.0
{
return Err(RopeKnobError::Knob);
}
let mut cfg = RopeScaling::default();
if let Some(kind) = knobs.scaling {
cfg.kind = kind;
} else if let Some(t) = model.scaling_type.as_deref().filter(|t| !t.is_empty()) {
match RopeScalingType::parse(t) {
Some(kind) => cfg.kind = kind,
None => return Err(RopeKnobError::ModelType(t.to_owned())),
}
}
if knobs.rope_scale > 0.0 {
cfg.factor = knobs.rope_scale;
} else if model.factor > 1.0 {
cfg.factor = model.factor;
}
if knobs.rope_freq_base > 0.0 {
cfg.freq_base = knobs.rope_freq_base;
} else if model.freq_base > 1.0 {
cfg.freq_base = model.freq_base;
}
if knobs.yarn_orig_ctx > 0.0 {
cfg.orig_ctx = knobs.yarn_orig_ctx;
} else if model.orig_ctx >= 1.0 {
cfg.orig_ctx = model.orig_ctx;
}
cfg.freq_scale_in = knobs.rope_freq_scale;
cfg.ext_factor = if knobs.yarn_ext_factor >= 0.0 {
knobs.yarn_ext_factor
} else if cfg.kind == RopeScalingType::YaRN {
1.0
} else {
0.0
};
cfg.attn_factor = knobs.yarn_attn_factor;
cfg.beta_fast = knobs.yarn_beta_fast;
cfg.beta_slow = knobs.yarn_beta_slow;
let mut inert = false;
if cfg.kind == RopeScalingType::None {
inert = knobs.rope_scale > 1.0
|| knobs.rope_freq_scale > 0.0
|| knobs.yarn_ext_factor > 0.0
|| knobs.yarn_attn_factor != 1.0;
let base = cfg.freq_base;
cfg = RopeScaling {
freq_base: base,
..RopeScaling::default()
};
}
cfg.validate().map_err(RopeKnobError::Invalid)?;
Ok(ResolvedRope {
scaling: cfg,
inert_knobs_ignored: inert,
})
}
/// `setup.py::derived_factor`: final context over the trained one, at least 1.
pub fn derived_factor(ctx: u64, trained: u64) -> f64 {
(ctx as f64 / trained as f64).max(1.0)
}
/// Why `setup.py::resolve_rope` refuses a combination.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SetupRopeError {
/// `--rope-scale` with no method inside the trained range: nothing to scale.
ScaleWithoutMethod,
/// `--rope-scaling none` past the trained range: the stock angles are out of spec there.
NoneBeyondTrained,
}
impl fmt::Display for SetupRopeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::ScaleWithoutMethod => f.write_str(
"--rope-scale needs --rope-scaling linear or yarn (the chosen context fits the trained range, so there is nothing to scale)",
),
Self::NoneBeyondTrained => f.write_str(
"the context is past the model's trained range and --rope-scaling none keeps the stock angles there; pick yarn or linear, or lower the context",
),
}
}
}
impl std::error::Error for SetupRopeError {}
/// `setup.py::resolve_rope(ctx, scaling, scale, trained)`: `(scaling, scale)` for the context actually served;
/// `None` means "no scaling flags" (the stock model). `scaling = None` is the omitted flag.
pub fn setup_resolve_rope(
ctx: u64,
scaling: Option<RopeScalingType>,
scale: Option<f64>,
trained: u64,
) -> Result<Option<(RopeScalingType, f64)>, SetupRopeError> {
let none_or_absent = matches!(scaling, None | Some(RopeScalingType::None));
if ctx <= trained {
if scale.is_some() && none_or_absent {
return Err(SetupRopeError::ScaleWithoutMethod);
}
if none_or_absent {
return Ok(None);
}
let kind = scaling.unwrap_or(RopeScalingType::YaRN);
return Ok(Some((
kind,
scale.unwrap_or_else(|| derived_factor(ctx, trained)),
)));
}
if scaling == Some(RopeScalingType::None) {
return Err(SetupRopeError::NoneBeyondTrained);
}
Ok(Some((
scaling.unwrap_or(RopeScalingType::YaRN),
scale.unwrap_or_else(|| derived_factor(ctx, trained)),
)))
}
#[cfg(test)]
mod tests {
use super::*;
fn yarn(factor: f64) -> RopeScaling {
RopeScaling {
kind: RopeScalingType::YaRN,
factor,
ext_factor: 1.0,
..RopeScaling::default()
}
}
#[test]
fn default_is_identity() {
let d = RopeScaling::default();
assert_eq!(d.freq_scale(), 1.0);
assert_eq!(d.mscale(), 1.0);
assert_eq!(d.kernel_args(64), RopeKernelArgs::default());
assert_eq!(d.validate(), Ok(()));
}
#[test]
fn mscale_matches_yarn_temperature_for_factor_two() {
let s = yarn(2.0);
let want = 1.0 + 0.1 * 2.0f64.ln();
assert!((s.mscale() - want).abs() < 1e-15);
}
#[test]
fn corr_dims_are_clamped() {
let s = yarn(2.0);
let cd = s.corr_dims(4);
assert!(cd[0] >= 0.0 && cd[1] <= 3.0);
}
#[test]
fn non_finite_values_are_rejected_before_range_checks() {
let mut s = yarn(2.0);
s.factor = f64::NAN;
assert_eq!(s.validate(), Err(RopeScalingError::Factor));
s = yarn(2.0);
s.freq_base = f64::INFINITY;
assert_eq!(s.validate(), Err(RopeScalingError::FreqBase));
s = yarn(2.0);
s.beta_slow = f64::NAN;
assert_eq!(s.validate(), Err(RopeScalingError::Betas));
s = yarn(2.0);
s.attn_factor = f64::NAN;
assert_eq!(s.validate(), Err(RopeScalingError::AttnFactor));
// none ignores every knob except the base
let n = RopeScaling {
factor: f64::NAN,
beta_fast: -1.0,
..RopeScaling::default()
};
assert_eq!(n.validate(), Ok(()));
}
#[test]
fn table_is_prefix_stable_and_chunkable() {
let s = yarn(2.0);
let big = build_rope_table(64, &s, 300).unwrap();
let small = build_rope_table(64, &s, 17).unwrap();
assert_eq!(&big.cos[..small.cos.len()], &small.cos[..]);
assert_eq!(&big.sin[..small.sin.len()], &small.sin[..]);
let mut c = vec![0.0; 10 * 32];
let mut sn = vec![0.0; 10 * 32];
fill_rope_table(64, &s, 123, &mut c, &mut sn).unwrap();
assert_eq!(&big.cos[123 * 32..133 * 32], &c[..]);
assert_eq!(&big.sin[123 * 32..133 * 32], &sn[..]);
}
#[test]
fn position_zero_exposes_mscale() {
let t = build_rope_table(64, &yarn(2.0), 2).unwrap();
let ms = yarn(2.0).mscale() as f32;
assert!(t.row_cos(0).iter().all(|&c| (c - ms).abs() <= f32::EPSILON));
assert!(t.row_sin(0).iter().all(|&s| s == 0.0));
}
#[test]
fn bad_shapes_and_configs_are_refused() {
assert_eq!(
build_rope_table(63, &RopeScaling::default(), 1),
Err(RopeTableError::NRot(63))
);
assert_eq!(
build_rope_table(0, &RopeScaling::default(), 1),
Err(RopeTableError::NRot(0))
);
let bad = yarn(0.5);
assert!(matches!(
build_rope_table(64, &bad, 1),
Err(RopeTableError::Config(RopeScalingError::Factor))
));
let mut c = vec![0.0; 33];
let mut s = vec![0.0; 33];
assert_eq!(
fill_rope_table(64, &RopeScaling::default(), 0, &mut c, &mut s),
Err(RopeTableError::BufferLength)
);
}
#[test]
fn table_bytes_for_charter_contexts() {
assert_eq!(rope_table_bytes(64, 524_288), Some(134_217_728));
assert_eq!(rope_table_bytes(64, 262_144), Some(67_108_864));
}
#[test]
fn setup_resolution_matches_setup_py() {
use RopeScalingType::{Linear, YaRN};
let nn = Some(RopeScalingType::None);
let t = TRAINED_CONTEXT;
assert_eq!(setup_resolve_rope(t, None, None, t), Ok(None));
assert_eq!(setup_resolve_rope(t, nn, None, t), Ok(None));
assert_eq!(
setup_resolve_rope(t, None, Some(2.0), t),
Err(SetupRopeError::ScaleWithoutMethod)
);
assert_eq!(
setup_resolve_rope(t, Some(Linear), None, t),
Ok(Some((Linear, 1.0)))
);
assert_eq!(
setup_resolve_rope(524_288, None, None, t),
Ok(Some((YaRN, 2.0)))
);
assert_eq!(
setup_resolve_rope(393_216, None, None, t),
Ok(Some((YaRN, 1.5)))
);
assert_eq!(
setup_resolve_rope(524_288, Some(Linear), Some(3.0), t),
Ok(Some((Linear, 3.0)))
);
assert_eq!(
setup_resolve_rope(524_288, nn, None, t),
Err(SetupRopeError::NoneBeyondTrained)
);
}
#[test]
fn knob_resolution_follows_generate_cpp() {
// flag absent everywhere: stock model
let r = resolve_rope_scaling(&RopeKnobs::default(), &ModelRopeKeys::default()).unwrap();
assert_eq!(r.scaling, RopeScaling::default());
assert!(!r.inert_knobs_ignored);
// yarn factor 2: ext auto = 1
let k = RopeKnobs {
scaling: Some(RopeScalingType::YaRN),
rope_scale: 2.0,
..RopeKnobs::default()
};
let r = resolve_rope_scaling(&k, &ModelRopeKeys::default()).unwrap();
assert_eq!(r.scaling.kind, RopeScalingType::YaRN);
assert_eq!(r.scaling.factor, 2.0);
assert_eq!(r.scaling.ext_factor, 1.0);
// linear: ext auto = 0
let k = RopeKnobs {
scaling: Some(RopeScalingType::Linear),
rope_scale: 2.0,
..RopeKnobs::default()
};
assert_eq!(
resolve_rope_scaling(&k, &ModelRopeKeys::default())
.unwrap()
.scaling
.ext_factor,
0.0
);
// model file supplies defaults; an explicit none opts out and notes the dropped knobs
let model = ModelRopeKeys {
scaling_type: Some("yarn".into()),
factor: 2.0,
freq_base: 5e6,
orig_ctx: 131_072.0,
};
let r = resolve_rope_scaling(&RopeKnobs::default(), &model).unwrap();
assert_eq!(r.scaling.kind, RopeScalingType::YaRN);
assert_eq!(r.scaling.factor, 2.0);
assert_eq!(r.scaling.freq_base, 5e6);
assert_eq!(r.scaling.orig_ctx, 131_072.0);
let k = RopeKnobs {
scaling: Some(RopeScalingType::None),
rope_scale: 2.0,
..RopeKnobs::default()
};
let r = resolve_rope_scaling(&k, &model).unwrap();
assert_eq!(r.scaling.kind, RopeScalingType::None);
assert_eq!(r.scaling.freq_base, 5e6);
assert_eq!(r.scaling.factor, 1.0);
assert!(r.inert_knobs_ignored);
// refusals
let bad_scale = RopeKnobs {
rope_scale: 0.5,
..RopeKnobs::default()
};
assert_eq!(
resolve_rope_scaling(&bad_scale, &model),
Err(RopeKnobError::ScaleBelowOne)
);
let nan = RopeKnobs {
yarn_beta_fast: f64::NAN,
..RopeKnobs::default()
};
assert_eq!(
resolve_rope_scaling(&nan, &model),
Err(RopeKnobError::NotFinite)
);
let base1 = RopeKnobs {
rope_freq_base: 1.0,
..RopeKnobs::default()
};
assert_eq!(
resolve_rope_scaling(&base1, &model),
Err(RopeKnobError::FreqBase)
);
let neg = RopeKnobs {
yarn_attn_factor: 0.0,
..RopeKnobs::default()
};
assert_eq!(resolve_rope_scaling(&neg, &model), Err(RopeKnobError::Knob));
let weird = ModelRopeKeys {
scaling_type: Some("longrope".into()),
..ModelRopeKeys::default()
};
assert_eq!(
resolve_rope_scaling(&RopeKnobs::default(), &weird),
Err(RopeKnobError::ModelType("longrope".into()))
);
// a resolved factor that is fine per-flag but invalid as a whole
let k = RopeKnobs {
scaling: Some(RopeScalingType::YaRN),
rope_scale: 2.0,
rope_freq_scale: 1e6,
..RopeKnobs::default()
};
assert_eq!(
resolve_rope_scaling(&k, &ModelRopeKeys::default()),
Err(RopeKnobError::Invalid(RopeScalingError::Mscale))
);
}
}
@@ -0,0 +1,196 @@
// gen_rope_golden.cpp - golden-fixture generator for the Rust rope port (leleka-runtime::rope_scaling).
//
// It links the ORIGINAL host-side code: `include/strata/kernels/rope_scaling.hpp` is included unmodified, and the
// two `build_rope_table` definitions are extracted VERBATIM from `src/kernels/cuda/rope.cu` by `gen_rope_golden.sh`
// into a generated include (`rope_table_original.inc`). Nothing from the Original is re-typed here.
//
// Every double/float is printed as its IEEE bit pattern in hex so the fixture is exact (serde_json's default
// float parser is not guaranteed correctly rounded). Tables are summarised by FNV-1a 64 over the little-endian
// f32 bytes of the whole cos table and of the whole sin table, plus full rows at selected positions.
#include "strata/kernels/rope_scaling.hpp"
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <string>
#include <vector>
namespace strata::kernels {
// the engine's other definitions live in the .cu next to the extracted functions; only the table builders are needed
void build_rope_table(int n_rot, double theta, int max_pos, float* cos_tab, float* sin_tab);
void build_rope_table(int n_rot, const RopeScaling& sc, int max_pos, float* cos_tab, float* sin_tab);
} // namespace strata::kernels
namespace strata::kernels {
#include "rope_table_original.inc"
} // namespace strata::kernels
using namespace strata::kernels;
static std::string hex64(double d) {
uint64_t u;
std::memcpy(&u, &d, 8);
char b[32];
std::snprintf(b, sizeof b, "0x%016llx", (unsigned long long) u);
return b;
}
static std::string hex32(float f) {
uint32_t u;
std::memcpy(&u, &f, 4);
char b[32];
std::snprintf(b, sizeof b, "0x%08x", u);
return b;
}
static uint64_t fnv(const float* p, size_t n) {
uint64_t h = 0xcbf29ce484222325ull;
for (size_t i = 0; i < n; ++i) {
uint32_t u;
std::memcpy(&u, p + i, 4);
for (int k = 0; k < 4; ++k) {
h ^= (uint8_t) (u >> (8 * k));
h *= 0x100000001b3ull;
}
}
return h;
}
struct Case {
const char* name;
const char* desc;
int n_rot;
RopeScaling sc;
bool tables; // build the 524288-position tables (skipped for invalid configs)
};
static RopeScaling mk(RopeScalingType t, double fb, double factor, double fsi, double orig, double ext, double attn,
double bf, double bs) {
RopeScaling s;
s.type = t;
s.freq_base = fb;
s.factor = factor;
s.freq_scale_in = fsi;
s.orig_ctx = orig;
s.ext_factor = ext;
s.attn_factor = attn;
s.beta_fast = bf;
s.beta_slow = bs;
return s;
}
int main() {
using T = RopeScalingType;
const double B = 1e7, O = 262144;
std::vector<Case> cases = {
{"none_default", "default-constructed RopeScaling (today's engine)", 64, RopeScaling{}, true},
{"none_junk_knobs", "type none with every scaling knob set: knobs must be inert", 64,
mk(T::None, B, 4.0, 0.25, 4096, 1.0, 0.5, 20, 2), true},
{"linear_2", "linear factor 2 (512K over 262144)", 64, mk(T::Linear, B, 2.0, 0, O, 0, 1.0, 32, 1), true},
{"linear_1_5", "linear factor 1.5 (393216 over 262144)", 64, mk(T::Linear, B, 1.5, 0, O, 0, 1.0, 32, 1), true},
{"linear_freq_scale_in", "linear with the raw ggml freq_scale 0.25 overriding 1/factor", 64,
mk(T::Linear, B, 2.0, 0.25, O, 0, 1.0, 32, 1), true},
{"linear_attn_factor", "linear with attn_factor 0.9 and no correction: mscale = attn_factor", 64,
mk(T::Linear, B, 2.0, 0, O, 0, 0.9, 32, 1), true},
{"yarn_2", "yarn factor 2 (setup.py default for 512K), ext 1, betas 32/1", 64,
mk(T::YaRN, B, 2.0, 0, O, 1.0, 1.0, 32, 1), true},
{"yarn_1_5", "yarn factor 1.5 (setup.py default for 393216)", 64,
mk(T::YaRN, B, 1.5, 0, O, 1.0, 1.0, 32, 1), true},
{"yarn_1", "yarn factor 1 (inside trained range): ramp active, mscale 1", 64,
mk(T::YaRN, B, 1.0, 0, O, 1.0, 1.0, 32, 1), true},
{"yarn_4", "yarn factor 4 (1M context)", 64, mk(T::YaRN, B, 4.0, 0, O, 1.0, 1.0, 32, 1), true},
{"yarn_2_betas", "yarn factor 2 with attn 1.1, betas 16/2", 64, mk(T::YaRN, B, 2.0, 0, O, 1.0, 1.1, 16, 2), true},
{"yarn_2_ext_half", "yarn factor 2 with ext_factor 0.5", 64, mk(T::YaRN, B, 2.0, 0, O, 0.5, 1.0, 32, 1), true},
{"yarn_orig_131072", "yarn factor 4 against a 131072 trained context", 64,
mk(T::YaRN, B, 4.0, 0, 131072, 1.0, 1.0, 32, 1), true},
{"yarn_ext0", "yarn type with ext_factor 0: correction off, behaves as linear", 64,
mk(T::YaRN, B, 2.0, 0, O, 0.0, 1.0, 32, 1), true},
{"yarn_n_rot128", "yarn n_rot 128, base 1e6, orig 4096, factor 8", 128,
mk(T::YaRN, 1e6, 8.0, 0, 4096, 1.0, 1.0, 32, 1), true},
{"yarn_n_rot4", "yarn n_rot 4: corr_dims clamps to n_rot-1", 4, mk(T::YaRN, B, 2.0, 0, O, 1.0, 1.0, 32, 1), true},
// invalid (finite) configurations: only the validity message and the scalar resolutions are recorded
{"bad_factor_below_1", "factor 0.5", 64, mk(T::Linear, B, 0.5, 0, O, 0, 1.0, 32, 1), false},
{"bad_freq_base_1", "freq_base 1 (none)", 64, mk(T::None, 1.0, 1.0, 0, O, 0, 1.0, 32, 1), false},
{"bad_orig_ctx_0", "orig_ctx 0", 64, mk(T::YaRN, B, 2.0, 0, 0.0, 1.0, 1.0, 32, 1), false},
{"bad_ext_negative", "ext_factor -1", 64, mk(T::YaRN, B, 2.0, 0, O, -1.0, 1.0, 32, 1), false},
{"bad_attn_0", "attn_factor 0", 64, mk(T::Linear, B, 2.0, 0, O, 0, 0.0, 32, 1), false},
{"bad_beta_fast_0", "beta_fast 0", 64, mk(T::YaRN, B, 2.0, 0, O, 1.0, 1.0, 0, 1), false},
{"bad_beta_slow_neg", "beta_slow -1", 64, mk(T::YaRN, B, 2.0, 0, O, 1.0, 1.0, 32, -1), false},
{"bad_freq_scale_in_neg", "freq_scale_in -0.1", 64, mk(T::Linear, B, 2.0, -0.1, O, 0, 1.0, 32, 1), false},
{"bad_mscale_negative", "freq_scale_in 1e6 with ext 1: the log term drives mscale negative", 64,
mk(T::YaRN, B, 2.0, 1e6, O, 1.0, 1.0, 32, 1), false},
};
const int NMAX = 524288;
const int NS[2] = {262144, 524288};
const int SAMPLE_POS[] = {0, 1, 2, 4095, 4096, 65535, 131071, 262143, 262144, 524287};
const int AN_POS[] = {1, 4096, 262143, 524287};
std::printf("{\n \"generator\": \"gen_rope_golden.cpp over rope_scaling.hpp + rope.cu build_rope_table (verbatim)\",\n");
std::printf(" \"cases\": [\n");
std::vector<float> cs, sn;
for (size_t ci = 0; ci < cases.size(); ++ci) {
const Case& c = cases[ci];
const RopeScaling& s = c.sc;
const int half = c.n_rot / 2;
std::printf(" {\n \"name\": \"%s\", \"desc\": \"%s\", \"n_rot\": %d,\n", c.name, c.desc, c.n_rot);
const char* tn = s.type == T::YaRN ? "yarn" : s.type == T::Linear ? "linear" : "none";
std::printf(" \"type\": \"%s\",\n", tn);
std::printf(" \"freq_base\": \"%s\", \"factor\": \"%s\", \"freq_scale_in\": \"%s\", \"orig_ctx\": \"%s\",\n",
hex64(s.freq_base).c_str(), hex64(s.factor).c_str(), hex64(s.freq_scale_in).c_str(),
hex64(s.orig_ctx).c_str());
std::printf(" \"ext_factor\": \"%s\", \"attn_factor\": \"%s\", \"beta_fast\": \"%s\", \"beta_slow\": \"%s\",\n",
hex64(s.ext_factor).c_str(), hex64(s.attn_factor).c_str(), hex64(s.beta_fast).c_str(),
hex64(s.beta_slow).c_str());
const char* bad = rope_scaling_invalid(s);
if (bad) std::printf(" \"invalid\": \"%s\",\n", bad);
else std::printf(" \"invalid\": null,\n");
std::printf(" \"freq_scale\": \"%s\", \"mscale\": \"%s\",\n", hex64(s.freq_scale()).c_str(),
hex64(s.mscale()).c_str());
double cd[2];
s.corr_dims(c.n_rot, cd);
std::printf(" \"corr_dims\": [\"%s\", \"%s\"],\n", hex64(cd[0]).c_str(), hex64(cd[1]).c_str());
const RopeKernelArgs a = s.kernel_args(c.n_rot);
std::printf(" \"kernel_args\": {\"freq_scale\": \"%s\", \"corr_low\": \"%s\", \"corr_high\": \"%s\", "
"\"ext_factor\": \"%s\", \"attn_factor\": \"%s\"},\n",
hex32(a.freq_scale).c_str(), hex32(a.corr_low).c_str(), hex32(a.corr_high).c_str(),
hex32(a.ext_factor).c_str(), hex32(a.attn_factor).c_str());
// analytic path (float32 rope_scaled_angle): theta_extrap = (float)(p * inv_i)
std::printf(" \"analytic\": [");
bool first = true;
const int pairs[] = {0, 1, 7, 15, 16, 31};
for (int pair : pairs) {
if (pair >= half) continue;
for (int p : AN_POS) {
const double inv = std::pow(s.freq_base, -2.0 * (double) pair / (double) c.n_rot);
const float te = (float) ((double) p * inv);
float co, si;
rope_scaled_angle(te, a.freq_scale, a.corr_low, a.corr_high, a.ext_factor, a.attn_factor, pair, co, si);
std::printf("%s\n {\"theta_extrap\": \"%s\", \"pair\": %d, \"cos\": \"%s\", \"sin\": \"%s\"}",
first ? "" : ",", hex32(te).c_str(), pair, hex32(co).c_str(), hex32(si).c_str());
first = false;
}
}
std::printf("\n ]");
if (c.tables) {
cs.assign((size_t) NMAX * half, 0.f);
sn.assign((size_t) NMAX * half, 0.f);
build_rope_table(c.n_rot, s, NMAX, cs.data(), sn.data());
std::printf(",\n \"tables\": [");
for (int k = 0; k < 2; ++k)
std::printf("%s\n {\"n_pos\": %d, \"cos_fnv1a64\": \"0x%016llx\", \"sin_fnv1a64\": \"0x%016llx\"}",
k ? "," : "", NS[k], (unsigned long long) fnv(cs.data(), (size_t) NS[k] * half),
(unsigned long long) fnv(sn.data(), (size_t) NS[k] * half));
std::printf("\n ],\n \"rows\": [");
for (size_t k = 0; k < sizeof SAMPLE_POS / sizeof *SAMPLE_POS; ++k) {
const int p = SAMPLE_POS[k];
std::printf("%s\n {\"pos\": %d, \"cos\": [", k ? "," : "", p);
for (int i = 0; i < half; ++i) std::printf("%s\"%s\"", i ? "," : "", hex32(cs[(size_t) p * half + i]).c_str());
std::printf("], \"sin\": [");
for (int i = 0; i < half; ++i) std::printf("%s\"%s\"", i ? "," : "", hex32(sn[(size_t) p * half + i]).c_str());
std::printf("]}");
}
std::printf("\n ]");
}
std::printf("\n }%s\n", ci + 1 < cases.size() ? "," : "");
}
std::printf(" ]\n}\n");
return 0;
}
@@ -0,0 +1,19 @@
#!/bin/sh
# Regenerates rope_golden.json from the Original's host code (macOS or Linux, any C++17 compiler).
# usage: gen_rope_golden.sh [extra compiler flags]
# The committed fixture is built with -O2 -ffp-contract=off (Rust never fuses multiply-adds) and
# -fno-builtin-sinf/-cosf: Apple clang otherwise merges a sinf+cosf pair into __sincosf_stret, whose sinf
# differs from a separate sinf call by 1-2 ULP, and Rust (like the CUDA device code) calls them separately.
# Only the float32 analytic path is affected; the float64 tables are identical either way.
set -eu
here=$(cd "$(dirname "$0")" && pwd)
strata="$here/../../../../engine/strata"
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
# extract the two build_rope_table definitions from rope.cu verbatim (up to the next anonymous namespace)
awk '/^void build_rope_table\(int n_rot, double theta/ {on=1} on && /^namespace \{/ {exit} on {print}' \
"$strata/src/kernels/cuda/rope.cu" > "$work/rope_table_original.inc"
test -s "$work/rope_table_original.inc"
${CXX:-clang++} -std=c++17 -O2 -ffp-contract=off -fno-builtin-sinf -fno-builtin-cosf "$@" -I"$strata/include" -I"$work" \
"$here/gen_rope_golden.cpp" -o "$work/gen_rope_golden"
"$work/gen_rope_golden" > "$here/rope_golden.json"
File diff suppressed because it is too large Load Diff