Files
leleka/crates/sampler-ref/tests/oracle.rs
T
Pavlo RatushnyiandClaude Sonnet 5.5 45bad22b88 feat(sampler-ref): CPU reference of the Original sampler chain with host-oracle fixtures
New pure-Rust crate leleka-sampler-ref: Philox draw, penalties -> top_k ->
top_p -> min_p -> temperature -> inverse-CDF pick, greedy argmax, coupled-draft
counter/ring math, penalty_rows, exact-match acceptance, and the request-level
SamplingParams validation with the Original's GEN defaults and wire keys.

Golden fixtures come from compiling the Original's sampler_parity.cpp host
reference (included unmodified) and sampler/coupled_draft headers with clang++
(-ffp-contract=off), plus the verbatim StrataEngine.sampling_keys lifted from
server.py. No GPU, no speed or quality claim.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-14 14:42:51 +02:00

227 lines
7.3 KiB
Rust

//! The Rust reference against golden fixtures produced by the Original's host
//! sampler logic (see `oracle/gen_fixtures.cpp`). Floats travel as binary32 bit
//! patterns, so every comparison here is bitwise on the integer/RNG side and on
//! the selected list; picks follow from them.
use leleka_sampler_ref::chain::{
SamplerParams, penalised_logits, penalty_window, sample_row, sampled_k, select_topk,
};
use leleka_sampler_ref::coupled::{
coupled_draft_cell, coupled_draft_counter, coupled_draft_sample, coupled_hist_base,
coupled_hist_len, coupled_hist_start, penalty_rows,
};
use leleka_sampler_ref::philox::philox_uniform;
use serde_json::Value;
fn fixtures() -> Value {
let text = include_str!("fixtures/sampler_oracle.json");
serde_json::from_str(text).expect("fixture JSON")
}
fn u32s(v: &Value) -> Vec<u32> {
v.as_array()
.unwrap()
.iter()
.map(|x| x.as_u64().unwrap() as u32)
.collect()
}
fn floats(v: &Value) -> Vec<f32> {
u32s(v).into_iter().map(f32::from_bits).collect()
}
fn ints(v: &Value) -> Vec<i32> {
v.as_array()
.unwrap()
.iter()
.map(|x| x.as_i64().unwrap() as i32)
.collect()
}
fn params(v: &Value) -> SamplerParams {
let f = |k: &str| f32::from_bits(v[k].as_u64().unwrap() as u32);
SamplerParams {
top_k: v["top_k"].as_i64().unwrap() as i32,
top_p: f("top_p"),
min_p: f("min_p"),
temperature: f("temperature"),
min_keep: v["min_keep"].as_i64().unwrap() as i32,
penalty_last_n: v["penalty_last_n"].as_i64().unwrap() as i32,
penalty_repeat: f("penalty_repeat"),
penalty_freq: f("penalty_freq"),
penalty_present: f("penalty_present"),
seed: v["seed"].as_u64().unwrap(),
counter: v["counter"].as_u64().unwrap(),
greedy: v["greedy"].as_bool().unwrap(),
}
}
fn case_logits(case: &Value) -> Vec<f32> {
if let Some(sparse) = case.get("sparse") {
let mut l = vec![
f32::from_bits(sparse["fill"].as_u64().unwrap() as u32);
case["n_vocab"].as_u64().unwrap() as usize
];
for pair in sparse["set"].as_array().unwrap() {
l[pair[0].as_u64().unwrap() as usize] =
f32::from_bits(pair[1].as_u64().unwrap() as u32);
}
l
} else {
floats(&case["logits"])
}
}
#[test]
fn philox_matches_the_original_host_twin() {
let f = fixtures();
let rows = f["philox"].as_array().unwrap();
assert!(rows.len() >= 80);
for r in rows {
let (seed, counter, bits) = (
r[0].as_u64().unwrap(),
r[1].as_u64().unwrap(),
r[2].as_u64().unwrap() as u32,
);
assert_eq!(
philox_uniform(seed, counter).to_bits(),
bits,
"seed {seed} counter {counter}"
);
}
}
#[test]
fn chain_matches_the_original_bit_for_bit() {
let f = fixtures();
let cases = f["chain"].as_array().unwrap();
assert!(cases.len() >= 150);
let mut sampled = 0;
let mut greedy = 0;
for case in cases {
let name = case["name"].as_str().unwrap();
let p = params(&case["params"]);
let logits = case_logits(case);
let history = ints(&case["history"]);
let row = case["row"].as_u64().unwrap();
let expect = &case["expect"];
// the selection list, bitwise
let window = penalty_window(&history, p.penalty_last_n);
let scores = penalised_logits(&logits, window, &p);
let is_greedy = p.is_greedy();
let k = if is_greedy {
1
} else {
sampled_k(p.top_k, logits.len())
};
let sel = select_topk(&scores, k);
assert_eq!(sel.ids, ints(&expect["sel_ids"]), "{name}: selection ids");
let got: Vec<u32> = sel.logits.iter().map(|x| x.to_bits()).collect();
assert_eq!(got, u32s(&expect["sel_logits"]), "{name}: selection logits");
// the token
let token = sample_row(&logits, &history, &p, row).unwrap();
assert_eq!(
token,
expect["token"].as_i64().unwrap() as i32,
"{name}: token"
);
if is_greedy {
greedy += 1;
} else {
sampled += 1;
let u = philox_uniform(p.seed, p.counter.wrapping_add(row));
assert_eq!(
u.to_bits(),
expect["u"].as_u64().unwrap() as u32,
"{name}: uniform"
);
}
}
assert!(
sampled > 100 && greedy > 10,
"sampled {sampled}, greedy {greedy}"
);
}
#[test]
fn counter_arithmetic_matches_the_original_headers() {
let f = fixtures();
let c = &f["counters"];
for r in c["cells"].as_array().unwrap() {
let (p, a, j) = (
r[0].as_i64().unwrap(),
r[1].as_i64().unwrap() as i32,
r[2].as_i64().unwrap() as i32,
);
let cell = coupled_draft_cell(p, a, j);
assert_eq!(cell, r[3].as_i64().unwrap());
assert_eq!(coupled_draft_counter(cell), r[4].as_u64().unwrap());
}
for r in c["hist_len"].as_array().unwrap() {
let v = ints(r);
assert_eq!(coupled_hist_len(v[0], v[1]), v[2], "hist_len {v:?}");
}
for r in c["hist_start"].as_array().unwrap() {
let v = ints(r);
assert_eq!(
coupled_hist_start(v[0], v[1], v[2]),
v[3],
"hist_start {v:?}"
);
}
}
#[test]
fn penalty_rows_and_ring_base_match_the_original() {
let f = fixtures();
for case in f["penalty_rows"].as_array().unwrap() {
let tail = ints(&case["tail"]);
let window = ints(&case["window"]);
let h = case["h"].as_u64().unwrap() as usize;
assert_eq!(
penalty_rows(&tail, &window, window.len(), h),
ints(&case["rows"])
);
let next = case["next"].as_i64().unwrap() as i32;
assert_eq!(
coupled_hist_base(&tail, next, h as i32),
ints(&case["base"])
);
}
}
#[test]
fn coupled_draft_matches_the_transcribed_kernels() {
let f = fixtures();
let cases = f["coupled"].as_array().unwrap();
assert!(cases.len() >= 50);
let mut sampled = 0;
for case in cases {
let cap = case["cap"].as_i64().unwrap() as i32;
let j = case["j"].as_i64().unwrap() as i32;
let step0 = case["step0"].as_i64().unwrap() as i32;
let id_vocab = case["id_vocab"].as_u64().unwrap() as usize;
let p = params(&case["params"]);
let mut logits = floats(&case["logits"]);
let sub_to_id = ints(&case["sub_to_id"]);
let id_to_sub = ints(&case["id_to_sub"]);
let mut ring = ints(&case["ring"]);
let got = coupled_draft_sample(
&mut logits,
(!sub_to_id.is_empty()).then_some(&sub_to_id[..]),
(!id_to_sub.is_empty()).then_some(&id_to_sub[..]),
id_vocab,
&p,
&mut ring,
cap,
j,
step0,
);
let e = &case["expect"];
assert_eq!(got.id, e["id"].as_i64().unwrap() as i32);
assert_eq!(got.sub_index, e["sub"].as_i64().unwrap() as i32);
assert_eq!(got.prob.to_bits(), e["prob"].as_u64().unwrap() as u32);
assert_eq!(ring[(cap + j) as usize], got.id);
if !p.is_greedy() {
sampled += 1;
}
}
assert!(sampled > 40);
}