New crate leleka-offline-tools wired as 'strata-next tools ...'. Every output is byte-identical to the unmodified Python tool (scripts/offline/diff_tools.py: packs incl. refusal cases, 14 draft-vocab subsets x out/stats, make_profile at 512/256/8 experts with ranked bases and traces, mtp_rt at the real H/FF geometry). Committed tiny goldens + integration tests; mtp_rt's multi-MB input is regenerated from a shared splitmix64 rule. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
340 lines
11 KiB
Rust
340 lines
11 KiB
Rust
//! The ported tools against the Python originals' exact outputs.
|
|
//!
|
|
//! `tests/fixtures/tools_oracle.json` is written by `scripts/offline/gen_goldens.py tools_oracle`, which runs the
|
|
//! unmodified `engine/strata/tools/{embd_bf16_pack,ple_fp8_pack,draft_vocab,make_profile,mtp_rt}.py` on tiny
|
|
//! synthetic inputs. `scripts/offline/diff_tools.py` is the live differential over more cases.
|
|
use std::{fs, 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);
|
|
}
|
|
|
|
#[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() {
|
|
let base = 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
|
|
});
|
|
let out = root.join("out.bin");
|
|
let printed = draft_vocab::run(&draft_vocab::Options {
|
|
gguf: &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}");
|
|
}
|
|
let _ = fs::remove_dir_all(root);
|
|
}
|
|
|
|
#[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() {
|
|
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()
|
|
);
|
|
}
|
|
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());
|
|
}
|
|
|
|
fn mtp_fixture(seed: u64, n_expert: usize) -> Vec<u8> {
|
|
let (h, ff) = (mtp_rt::H, mtp_rt::FF);
|
|
let mut rng = SplitMix(seed);
|
|
let bf = |rng: &mut SplitMix, n: usize| -> Vec<u8> {
|
|
rng.bf16(n).iter().flat_map(|v| v.to_le_bytes()).collect()
|
|
};
|
|
let f32s = |rng: &mut SplitMix, n: usize| -> Vec<u8> {
|
|
rng.bf16(n)
|
|
.iter()
|
|
.flat_map(|v| (u32::from(*v) << 16).to_le_bytes())
|
|
.collect()
|
|
};
|
|
let gate_up = rng.bytes(n_expert * 2 * ff * (h / 64) * 18);
|
|
let embedding = bf(&mut rng, 64 * 8);
|
|
let hidden_norm = f32s(&mut rng, 24);
|
|
let down = rng.bytes(n_expert * h * (ff / 64) * 18);
|
|
let q_proj = bf(&mut rng, 32 * 6);
|
|
let gate = bf(&mut rng, 16 * 4);
|
|
let q_norm = f32s(&mut rng, 16);
|
|
let shared = bf(&mut rng, 96 * 5);
|
|
let mixer = bf(&mut rng, 40 * 3);
|
|
let e = n_expert as u64;
|
|
#[allow(clippy::type_complexity)]
|
|
let tensors: Vec<(&str, Vec<u64>, u32, Vec<u8>)> = 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, embedding),
|
|
("mtp.pre_fc_norm_hidden.weight", vec![24], 0, hidden_norm),
|
|
(
|
|
"mtp.layers.0.mlp.experts.down_proj",
|
|
vec![ff as u64, h as u64, e],
|
|
42,
|
|
down,
|
|
),
|
|
(
|
|
"mtp.layers.0.self_attn.q_proj.weight",
|
|
vec![32, 6],
|
|
30,
|
|
q_proj,
|
|
),
|
|
("mtp.layers.0.mlp.gate.weight", vec![16, 4], 30, gate),
|
|
("mtp.layers.0.self_attn.q_norm.weight", vec![16], 0, q_norm),
|
|
(
|
|
"mtp.layers.0.mlp.shared_expert.down_proj.weight",
|
|
vec![96, 5],
|
|
30,
|
|
shared,
|
|
),
|
|
(
|
|
"mtp.hyper_connection_mixer.input_mix_weight_up.weight",
|
|
vec![40, 3],
|
|
30,
|
|
mixer,
|
|
),
|
|
];
|
|
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);
|
|
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]);
|
|
}
|