Files
leleka/crates/offline-tools/tests/oracle.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

298 lines
11 KiB
Rust

//! The ported tools against the Python originals' exact outputs.
//!
//! `tests/fixtures/tools_oracle.json` was recorded by running the
//! unmodified `Strata 41cf05a0, tools/{embd_bf16_pack,ple_fp8_pack,draft_vocab,make_profile,mtp_rt}.py` on tiny
//! synthetic inputs.
use std::{
fs,
path::{Path, PathBuf},
};
use leleka_offline_tools::{draft_vocab, make_profile, mtp_rt, packs};
use serde_json::Value;
use sha2::{Digest, Sha256};
fn golden() -> Value {
serde_json::from_str(include_str!("fixtures/tools_oracle.json")).unwrap()
}
fn unhex(text: &str) -> Vec<u8> {
(0..text.len() / 2).map(|i| u8::from_str_radix(&text[i * 2..i * 2 + 2], 16).unwrap()).collect()
}
fn scratch(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("offline-tools-{}-{name}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
dir
}
fn checkpoint(spec: &Value, root: &std::path::Path) -> PathBuf {
let model = root.join("ckpt");
fs::create_dir_all(&model).unwrap();
for (name, hex) in spec["files"].as_object().unwrap() {
fs::write(model.join(name), unhex(hex.as_str().unwrap())).unwrap();
}
model
}
#[test]
fn embd_and_ple_packs_are_byte_identical() {
let golden = golden();
for (kind, run) in
[("embd", packs::embd_bf16_pack as fn(&std::path::Path, &std::path::Path) -> _), ("ple", packs::ple_fp8_pack)]
{
let root = scratch(kind);
let model = checkpoint(&golden[kind], &root);
let out = root.join("out.gguf");
run(&model, &out).unwrap();
assert_eq!(fs::read(&out).unwrap(), unhex(golden[kind]["output"].as_str().unwrap()), "{kind}");
assert!(!root.join("out.gguf.part").exists());
let _ = fs::remove_dir_all(root);
}
}
#[test]
fn embd_refuses_a_non_bf16_table() {
let root = scratch("refuse");
let golden = golden();
let model = checkpoint(&golden["embd"], &root);
// flip the dtype in the safetensors header: "BF16" -> "F16 " would change the length, so use a longer name
let shard = model.join("model-00001.safetensors");
let text = String::from_utf8_lossy(&fs::read(&shard).unwrap()).replace("\"BF16\"", "\"FP16\"");
let mut bytes = fs::read(&shard).unwrap();
let n = u64::from_le_bytes(bytes[0..8].try_into().unwrap()) as usize;
let header = text[8..8 + n].to_owned();
bytes[8..8 + n].copy_from_slice(header.as_bytes());
fs::write(&shard, bytes).unwrap();
assert!(packs::embd_bf16_pack(&model, &root.join("a.gguf")).is_err());
assert!(!root.join("a.gguf").exists());
let _ = fs::remove_dir_all(root);
}
/// Writes the case's base ids to `base.bin` when the case has any.
fn write_draft_base(root: &Path, case: &Value) -> Option<PathBuf> {
case["base"].as_array().map(|ids| {
let path = root.join("base.bin");
let bytes: Vec<u8> = ids.iter().flat_map(|i| (i.as_i64().unwrap() as i32).to_le_bytes()).collect();
fs::write(&path, bytes).unwrap();
path
})
}
fn check_draft_case(root: &Path, gguf: &Path, case: &Value) {
let base = write_draft_base(root, case);
let out = root.join("out.bin");
let printed = draft_vocab::run(&draft_vocab::Options {
gguf,
base: base.as_deref(),
add: case["add"].as_str().unwrap(),
out: Some(&out),
stats: true,
})
.unwrap();
assert_eq!(fs::read(&out).unwrap(), unhex(case["output"].as_str().unwrap()), "{case}");
let lines: Vec<&str> = printed.lines().filter(|l| !l.starts_with("wrote ")).collect();
let wanted: Vec<&str> = case["printed"].as_array().unwrap().iter().map(|l| l.as_str().unwrap()).collect();
assert_eq!(lines, wanted, "{case}");
}
#[test]
fn draft_vocab_subsets_match_the_oracle() {
let golden = golden();
let root = scratch("draft");
let gguf = root.join("vocab.gguf");
fs::write(&gguf, unhex(golden["draft_vocab"]["gguf"].as_str().unwrap())).unwrap();
for case in golden["draft_vocab"]["cases"].as_array().unwrap() {
check_draft_case(&root, &gguf, case);
}
let _ = fs::remove_dir_all(root);
}
fn check_profile_run(root: &Path, run: &Value, n_expert: usize) {
let out = root.join("p.bin");
let base = root.join("base.prof");
let trace = root.join("trace.bin");
let summary = make_profile::run(&make_profile::Options {
traces: &[trace.as_path()],
base: run["base"].as_bool().unwrap().then_some(base.as_path()),
out: &out,
n_expert,
})
.unwrap();
assert_eq!(fs::read(&out).unwrap(), unhex(run["output"].as_str().unwrap()));
assert_eq!(summary.split_once(": ").unwrap().1.trim(), run["summary"].as_str().unwrap());
}
#[test]
fn expert_profiles_match_the_oracle() {
let golden = golden();
let spec = &golden["make_profile"];
let n_expert = spec["n_expert"].as_u64().unwrap() as usize;
let root = scratch("profile");
fs::write(root.join("base.prof"), unhex(spec["base"].as_str().unwrap())).unwrap();
fs::write(root.join("trace.bin"), unhex(spec["trace"].as_str().unwrap())).unwrap();
for run in spec["runs"].as_array().unwrap() {
check_profile_run(&root, run, n_expert);
}
let _ = fs::remove_dir_all(root);
}
// ---- mtp_rt: the input is regenerated from the oracle script's splitmix64 rules ----
struct SplitMix(u64);
impl SplitMix {
fn next(&mut self) -> u64 {
self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = self.0;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^ (z >> 31)
}
fn bytes(&mut self, n: usize) -> Vec<u8> {
let mut out = Vec::with_capacity(n + 8);
while out.len() < n {
out.extend_from_slice(&self.next().to_le_bytes());
}
out.truncate(n);
out
}
fn bf16(&mut self, n: usize) -> Vec<u16> {
(0..n)
.map(|_| {
let r = self.next();
(((r & 1) << 15) | ((0x70 + (r >> 1) % 0x12) << 7) | ((r >> 40) & 0x7F)) as u16
})
.collect()
}
}
fn gguf_string(out: &mut Vec<u8>, s: &str) {
out.extend_from_slice(&(s.len() as u64).to_le_bytes());
out.extend_from_slice(s.as_bytes());
}
/// How a fixture tensor's bytes are drawn from the generator.
enum Fill {
Bytes(usize),
Bf16(usize),
F32(usize),
}
type FixtureTensor = (&'static str, Vec<u64>, u32, Fill);
impl Fill {
fn draw(&self, rng: &mut SplitMix) -> Vec<u8> {
match *self {
Fill::Bytes(n) => rng.bytes(n),
Fill::Bf16(n) => rng.bf16(n).iter().flat_map(|v| v.to_le_bytes()).collect(),
Fill::F32(n) => rng.bf16(n).iter().flat_map(|v| (u32::from(*v) << 16).to_le_bytes()).collect(),
}
}
}
/// The experts and the first dense tensors, in the order the oracle draws them.
fn mtp_leading_layout(n_expert: usize) -> Vec<FixtureTensor> {
let (h, ff) = (mtp_rt::H, mtp_rt::FF);
let e = n_expert as u64;
let gate_up = Fill::Bytes(n_expert * 2 * ff * (h / 64) * 18);
let down = Fill::Bytes(n_expert * h * (ff / 64) * 18);
vec![
("mtp.layers.0.mlp.experts.gate_up_proj", vec![h as u64, 2 * ff as u64, e], 42, gate_up),
("mtp.fc_embedding.weight", vec![64, 8], 30, Fill::Bf16(64 * 8)),
("mtp.pre_fc_norm_hidden.weight", vec![24], 0, Fill::F32(24)),
("mtp.layers.0.mlp.experts.down_proj", vec![ff as u64, h as u64, e], 42, down),
]
}
/// The remaining dense tensors, in the order the oracle draws them.
fn mtp_trailing_layout() -> Vec<FixtureTensor> {
vec![
("mtp.layers.0.self_attn.q_proj.weight", vec![32, 6], 30, Fill::Bf16(32 * 6)),
("mtp.layers.0.mlp.gate.weight", vec![16, 4], 30, Fill::Bf16(16 * 4)),
("mtp.layers.0.self_attn.q_norm.weight", vec![16], 0, Fill::F32(16)),
("mtp.layers.0.mlp.shared_expert.down_proj.weight", vec![96, 5], 30, Fill::Bf16(96 * 5)),
("mtp.hyper_connection_mixer.input_mix_weight_up.weight", vec![40, 3], 30, Fill::Bf16(40 * 3)),
]
}
/// The GGUF header: one string KV and the tensor infos, padded to 32 bytes.
fn mtp_header(tensors: &[(&str, Vec<u64>, u32, Vec<u8>)]) -> Vec<u8> {
let mut head = b"GGUF".to_vec();
head.extend_from_slice(&3u32.to_le_bytes());
head.extend_from_slice(&(tensors.len() as u64).to_le_bytes());
head.extend_from_slice(&1u64.to_le_bytes());
gguf_string(&mut head, "general.architecture");
head.extend_from_slice(&8u32.to_le_bytes());
gguf_string(&mut head, "qwen4exp-mtp");
let mut offset = 0u64;
for (name, dims, kind, data) in tensors {
gguf_string(&mut head, name);
head.extend_from_slice(&(dims.len() as u32).to_le_bytes());
for d in dims {
head.extend_from_slice(&d.to_le_bytes());
}
head.extend_from_slice(&kind.to_le_bytes());
head.extend_from_slice(&offset.to_le_bytes());
offset += (data.len() as u64).next_multiple_of(32);
}
head.resize(head.len().next_multiple_of(32), 0);
head
}
fn mtp_fixture(seed: u64, n_expert: usize) -> Vec<u8> {
let mut rng = SplitMix(seed);
let mut layout = mtp_leading_layout(n_expert);
layout.extend(mtp_trailing_layout());
let tensors: Vec<(&str, Vec<u64>, u32, Vec<u8>)> =
layout.into_iter().map(|(name, dims, kind, fill)| (name, dims, kind, fill.draw(&mut rng))).collect();
let mut head = mtp_header(&tensors);
for (_, _, _, data) in &tensors {
head.extend_from_slice(data);
head.resize(head.len().next_multiple_of(32), 0);
}
head
}
#[test]
fn mtp_runtime_files_match_the_oracle() {
let golden = golden();
let spec = &golden["mtp_rt"];
let n_expert = spec["n_expert"].as_u64().unwrap() as usize;
let root = scratch("mtp");
let gguf = root.join("mtp.gguf");
fs::write(&gguf, mtp_fixture(spec["seed"].as_u64().unwrap(), n_expert)).unwrap();
let out = root.join("rt");
let geometry = mtp_rt::Geometry { n_expert, ..Default::default() };
mtp_rt::run(&gguf, &out, &geometry).unwrap();
let sha = |name: &str| hex(&Sha256::digest(fs::read(out.join(name)).unwrap()));
assert_eq!(sha("experts.bin"), spec["experts_bin_sha256"].as_str().unwrap());
assert_eq!(sha("dense.bin"), spec["dense_bin_sha256"].as_str().unwrap());
assert_eq!(fs::read_to_string(out.join("dense.txt")).unwrap(), spec["dense_txt"].as_str().unwrap());
assert_eq!(fs::metadata(out.join("experts.bin")).unwrap().len() as usize, n_expert * geometry.blob());
let _ = fs::remove_dir_all(root);
}
fn hex(bytes: &[u8]) -> String {
bytes.iter().map(|b| format!("{b:02x}")).collect()
}
#[test]
fn q8_0_rounds_half_away_from_zero_like_the_numpy_original() {
// d = 127/127 = 1 -> inverse 1: every .5 value rounds away from zero
let mut block = [0.0f32; 32];
block[0] = 127.0;
block[1] = 0.5;
block[2] = -0.5;
block[3] = 1.5;
block[4] = -1.5;
block[5] = 0.49999997;
let out = mtp_rt::q8_0(&block);
assert_eq!(&out[..2], &0x3c00u16.to_le_bytes());
let quants: Vec<i8> = out[2..].iter().map(|b| *b as i8).collect();
assert_eq!(&quants[..6], &[127, 1, -1, 2, -2, 1]);
}