Files
leleka/crates/context/tests/rope_plan_golden.rs
T
Pavlo Ratushnyi da8c974f68 Drop the stale engine/strata paths and retired generator names from comments, doc strings and generated fixtures (STRA-407)
Rust comments that named scripts/offline/*, gen_goldens.py, oracle/gen_*.{sh,cpp,py}, build_oracle.sh and similar retired generators now say where the data
came from (the Original's code, Strata 41cf05a0) or drop the sentence. The path/generator text of seven generated fixtures (sampler_oracle.json, sampling_keys.json,
memory_plan_golden.json, rope_golden.json, cvec_oracle.json, stra161 fixtures.json, commentary-tool-prompt.json) is reworded; no test reads those fields and no pin
covers their bytes. cmd_time/doc.rs: the two path texts in the format string; its lines are re-broken so they stay within 120 columns (the string is unchanged
otherwise). Comment-only except those data/string spots; no behaviour change.
2026-11-23 22:37:17 +01:00

317 lines
12 KiB
Rust

//! Golden tests for `rope_scaling` and `memory_plan` against fixtures produced by the ORIGINAL's host code
//! (clang++ on macOS, arm64).
//!
//! Rope: the C++ side links `rope_scaling.hpp` unmodified and the two `build_rope_table` definitions extracted
//! verbatim from `rope.cu`, compiled `-O2 -ffp-contract=off`. Tables are checked bit-for-bit through FNV-1a 64
//! over all 524288 rows (and over the first 262144) plus ten full sample rows. The only libm-dependent
//! operations are pow/cos/sin/log (f64) and cosf/logf/sinf (f32): on macOS both sides call the same system
//! libm, so equality is exact there. On other platforms the hash result is reported but not asserted, and the
//! sample rows and analytic values are allowed 1 and 2 ULP respectively (documented, not measured here).
//!
//! Memory plan: the C++ side is the unmodified `strata-plan` CLI; stdout/stderr text is compared exactly.
#![allow(clippy::too_many_lines)]
use leleka_context::memory_plan::{
Costs, Geometry, KvFormat, KvShapes, PlanError, cli_pool, kv_pool_bytes, make_plan, make_plan_with_format,
state_bytes,
};
use leleka_context::rope_scaling::{RopeKernelArgs, RopeScaling, RopeScalingType, fill_rope_table, rope_scaled_angle};
use serde_json::Value;
const ROPE_JSON: &str = include_str!("rope_plan_golden/rope_golden.json");
const PLAN_JSON: &str = include_str!("rope_plan_golden/memory_plan_golden.json");
fn bits64(v: &Value) -> f64 {
let s = v.as_str().expect("hex string");
f64::from_bits(u64::from_str_radix(s.trim_start_matches("0x"), 16).unwrap())
}
fn bits32(v: &Value) -> f32 {
let s = v.as_str().expect("hex string");
f32::from_bits(u32::from_str_radix(s.trim_start_matches("0x"), 16).unwrap())
}
fn hex64(v: &Value) -> u64 {
u64::from_str_radix(v.as_str().unwrap().trim_start_matches("0x"), 16).unwrap()
}
fn ulp_diff(a: f32, b: f32) -> u32 {
if a.to_bits() == b.to_bits() {
return 0;
}
let map = |x: f32| {
let u = x.to_bits() as i64;
if u >= 0x8000_0000 { 0x8000_0000 - (u & 0x7fff_ffff) } else { u + 0x8000_0000 }
};
(map(a) - map(b)).unsigned_abs() as u32
}
const EXACT: bool = cfg!(target_os = "macos");
fn assert_close(what: &str, got: f32, want: f32, tol_ulp: u32) {
let tol = if EXACT { 0 } else { tol_ulp };
assert!(
ulp_diff(got, want) <= tol,
"{what}: got {:#010x} want {:#010x} ({} ulp, allowed {tol})",
got.to_bits(),
want.to_bits(),
ulp_diff(got, want)
);
}
fn config_of(c: &Value) -> RopeScaling {
RopeScaling {
kind: RopeScalingType::parse(c["type"].as_str().unwrap()).unwrap(),
freq_base: bits64(&c["freq_base"]),
factor: bits64(&c["factor"]),
freq_scale_in: bits64(&c["freq_scale_in"]),
orig_ctx: bits64(&c["orig_ctx"]),
ext_factor: bits64(&c["ext_factor"]),
attn_factor: bits64(&c["attn_factor"]),
beta_fast: bits64(&c["beta_fast"]),
beta_slow: bits64(&c["beta_slow"]),
}
}
struct Fnv(u64);
impl Fnv {
fn new() -> Self {
Self(0xcbf2_9ce4_8422_2325)
}
fn feed(&mut self, xs: &[f32]) {
for x in xs {
for b in x.to_bits().to_le_bytes() {
self.0 ^= u64::from(b);
self.0 = self.0.wrapping_mul(0x100_0000_01b3);
}
}
}
}
fn cases() -> Vec<Value> {
let root: Value = serde_json::from_str(ROPE_JSON).unwrap();
root["cases"].as_array().unwrap().clone()
}
/// Bit-exact, except that any NaN matches any NaN: an invalid YaRN config yields NaN from log(<0) and the sign of
/// that default NaN is a platform detail (the fixture was generated on arm64: 0x7fc00000; x86 SSE produces 0xffc00000).
fn same_f32(a: f32, b: f32) -> bool {
a.to_bits() == b.to_bits() || (a.is_nan() && b.is_nan())
}
fn check_scalars(c: &Value, sc: &RopeScaling, n_rot: i32) {
let name = c["name"].as_str().unwrap();
// validity message, exactly
let want = c["invalid"].as_str();
assert_eq!(sc.validate().err().map(|e| e.reason()), want, "{name}: validity");
check_scalar_resolutions(c, sc, n_rot, want.is_none());
let a = sc.kernel_args(n_rot);
check_kernel_args(c, name, &a);
check_analytic_path(c, name, &a);
}
fn check_scalar_resolutions(c: &Value, sc: &RopeScaling, n_rot: i32, valid: bool) {
let name = c["name"].as_str().unwrap();
// scalar resolutions: libm log is the only dependency
let tol = if EXACT { 0.0 } else { 4.0 * f64::EPSILON };
let near = |a: f64, b: f64| (a - b).abs() <= tol * b.abs().max(1.0);
assert!(near(sc.freq_scale(), bits64(&c["freq_scale"])), "{name}: freq_scale");
if valid || sc.freq_scale().is_finite() {
assert!(near(sc.mscale(), bits64(&c["mscale"])), "{name}: mscale");
}
let cd = sc.corr_dims(n_rot);
for k in 0..2 {
let want = bits64(&c["corr_dims"][k]);
// a NaN from log(<0) of an invalid config: any NaN matches (payload/sign are libm detail)
assert!(cd[k].to_bits() == want.to_bits() || (cd[k].is_nan() && want.is_nan()), "{name}: corr_dims[{k}]");
}
}
fn check_kernel_args(c: &Value, name: &str, a: &RopeKernelArgs) {
let w = &c["kernel_args"];
assert_eq!(a.freq_scale.to_bits(), bits32(&w["freq_scale"]).to_bits(), "{name}: args.freq_scale");
assert!(
same_f32(a.corr_low, bits32(&w["corr_low"])),
"{name}: args.corr_low: {:#010x} vs {:#010x}",
a.corr_low.to_bits(),
bits32(&w["corr_low"]).to_bits()
);
assert!(
same_f32(a.corr_high, bits32(&w["corr_high"])),
"{name}: args.corr_high: {:#010x} vs {:#010x}",
a.corr_high.to_bits(),
bits32(&w["corr_high"]).to_bits()
);
assert_eq!(a.ext_factor.to_bits(), bits32(&w["ext_factor"]).to_bits(), "{name}: args.ext_factor");
assert_eq!(a.attn_factor.to_bits(), bits32(&w["attn_factor"]).to_bits(), "{name}: args.attn_factor");
}
fn check_analytic_path(c: &Value, name: &str, a: &RopeKernelArgs) {
// analytic float32 path
for s in c["analytic"].as_array().unwrap() {
let (co, si) = rope_scaled_angle(bits32(&s["theta_extrap"]), a, s["pair"].as_i64().unwrap() as i32);
assert_close(&format!("{name}: analytic cos"), co, bits32(&s["cos"]), 2);
assert_close(&format!("{name}: analytic sin"), si, bits32(&s["sin"]), 2);
}
}
struct TableChunk<'a> {
name: &'a str,
first: usize,
half: usize,
cos: &'a [f32],
sin: &'a [f32],
}
fn check_sample_rows(samples: &[Value], chunk: &TableChunk) {
const CHUNK: usize = 4096;
let TableChunk { name, first, half, cos: cbuf, sin: sbuf } = *chunk;
for s in samples {
let p = s["pos"].as_u64().unwrap() as usize;
if p >= first && p < first + CHUNK {
let r = p - first;
for i in 0..half {
assert_close(&format!("{name}: row {p} cos[{i}]"), cbuf[r * half + i], bits32(&s["cos"][i]), 1);
assert_close(&format!("{name}: row {p} sin[{i}]"), sbuf[r * half + i], bits32(&s["sin"][i]), 1);
}
}
}
}
fn check_table_hashes(c: &Value, name: &str, got: [(u64, u64); 2]) {
let want = c["tables"].as_array().unwrap();
for (t, (gc, gs)) in want.iter().zip(got) {
let (wc, ws) = (hex64(&t["cos_fnv1a64"]), hex64(&t["sin_fnv1a64"]));
let n = t["n_pos"].as_u64().unwrap();
if EXACT {
assert_eq!(gc, wc, "{name}: cos table hash over {n} rows");
assert_eq!(gs, ws, "{name}: sin table hash over {n} rows");
} else if (gc, gs) != (wc, ws) {
eprintln!(
"note: {name}: table hash over {n} rows differs from the macOS fixture (non-macOS libm); \
sample rows are within tolerance"
);
}
}
}
fn check_tables(c: &Value, sc: &RopeScaling, n_rot: usize) {
let name = c["name"].as_str().unwrap();
let half = n_rot / 2;
const CHUNK: usize = 4096;
const N: usize = 524_288;
let samples = c["rows"].as_array().unwrap();
let mut cos_hash = Fnv::new();
let mut sin_hash = Fnv::new();
let mut at_262144 = (0, 0);
let mut cbuf = vec![0.0f32; CHUNK * half];
let mut sbuf = vec![0.0f32; CHUNK * half];
let mut first = 0;
while first < N {
fill_rope_table(n_rot, sc, first, &mut cbuf, &mut sbuf).unwrap();
if first == 262_144 {
at_262144 = (cos_hash.0, sin_hash.0);
}
check_sample_rows(samples, &TableChunk { name, first, half, cos: &cbuf, sin: &sbuf });
cos_hash.feed(&cbuf);
sin_hash.feed(&sbuf);
first += CHUNK;
}
check_table_hashes(c, name, [(at_262144.0, at_262144.1), (cos_hash.0, sin_hash.0)]);
}
fn run_case(name: &str) {
let c = cases().into_iter().find(|c| c["name"] == name).expect("case in fixture");
let sc = config_of(&c);
let n_rot = c["n_rot"].as_u64().unwrap() as usize;
check_scalars(&c, &sc, n_rot as i32);
if c.get("tables").is_some() {
check_tables(&c, &sc, n_rot);
}
}
macro_rules! rope_cases {
($($n:ident),* $(,)?) => { $( #[test] fn $n() { run_case(stringify!($n)); } )* };
}
rope_cases!(
none_default,
none_junk_knobs,
linear_2,
linear_1_5,
linear_freq_scale_in,
linear_attn_factor,
yarn_2,
yarn_1_5,
yarn_1,
yarn_4,
yarn_2_betas,
yarn_2_ext_half,
yarn_orig_131072,
yarn_ext0,
yarn_n_rot128,
yarn_n_rot4,
bad_factor_below_1,
bad_freq_base_1,
bad_orig_ctx_0,
bad_ext_negative,
bad_attn_0,
bad_beta_fast_0,
bad_beta_slow_neg,
bad_freq_scale_in_neg,
bad_mscale_negative,
);
// ---- memory plan -------------------------------------------------------------------------------
struct CliArgs {
ctx: u64,
free_vram: u64,
costs: Costs,
state_given: bool,
}
fn parse_cli(args: &[String]) -> Option<CliArgs> {
let mut cli = CliArgs { ctx: 20480, free_vram: 12_000_000_000, costs: Costs::default(), state_given: false };
let mut i = 0;
while i < args.len() {
let a = args[i].as_str();
let raw = args.get(i + 1)?;
let next = |i: &mut usize| -> u64 {
*i += 1;
raw.parse().expect("fixture numbers are plain u64")
};
match a {
"--max-context" => cli.ctx = next(&mut i),
"--vram" | "--pool" => cli.free_vram = next(&mut i),
"--dense" => cli.costs.dense_bytes = next(&mut i),
"--embd" => cli.costs.embd_bytes = next(&mut i),
"--workspace" => cli.costs.workspace_bytes = next(&mut i),
"--state" => {
cli.costs.state_bytes = next(&mut i);
cli.state_given = true;
}
_ => return None, // --help / unknown / missing value: argument parsing, not planner arithmetic
}
i += 1;
}
Some(cli)
}
fn interpret_cli(args: &[String]) -> Option<(i32, String, String)> {
let CliArgs { ctx, free_vram, mut costs, state_given } = parse_cli(args)?;
let g = Geometry::default();
if !state_given {
costs.state_bytes = state_bytes(&g).unwrap();
}
let pool = cli_pool(free_vram, &costs).unwrap();
Some(match make_plan(ctx, &g, &costs, pool) {
Ok(p) => {
// the format-generic path with INT8 must be the same plan
assert_eq!(make_plan_with_format(ctx, &g, KvFormat::Int8, &costs, pool).unwrap(), p);
(0, p.to_text(), String::new())
}
Err(e @ PlanError::DoesNotClose(_)) => (1, String::new(), format!("strata-plan: {e}\n")),
Err(e) => panic!("unexpected {e}"),
})
}
#[path = "rope_plan_golden/every_fixture_case_has.rs"]
mod every_fixture_case_has;