Files
leleka/crates/offline-tools/tests/oracle.rs
T
Pavlo Ratushnyi 056ab3d689 Retire the oracles, generators and scripts that only worked against the vendored Strata tree (STRA-406)
The vendored Strata tree engine/strata is removed for good (owner decision 2026-11-23): Leleka never builds or runs it, the vanilla
benchmark builds from its own checkout, the comparison measurements are finished and the CUDA ports are frozen. Everything below
compiled or read that tree, so it cannot run without it and is retired (the tree stays in git history, see third_party/strata/UPSTREAM.md).
Checked-in fixtures, golden JSON, sealed PTX, seal plans and MANIFEST hashes are untouched and keep being replayed by the cargo tests.

Drift guard
- crates/experimental-ref/tests/literal_port.rs: include_str! of the Original .cu files compared with the checked-in experimental ports.

Oracle generators and builders (they compile or extract from the Strata C++/Python sources; their outputs are the checked-in goldens)
- crates/experimental-ref/oracle/gen_{cvec,kv,remote,stream}_golden.{cpp,sh}, gen_seal_additions.py and the cuda_runtime stub they used
- crates/sampler-ref/oracle/build_oracle.sh, gen_fixtures.cpp, gen_sampling_keys.py, stub/ (run_port_host_tests.sh and the fixtures stay)
- crates/serving-policy/oracle/ (build_oracle.sh, gen_{host,cvec,vision}_fixtures.cpp)
- crates/context/tests/rope_plan_golden/gen_* (plan, rope, kv pool)
- crates/engine-core/src/conversation/golden/gen*.{sh,cpp} and stub/
- crates/cuda-driver/oracle/gen_prefill_ring_trace.py and drivers/prefill_ring_trace.cpp (extracted prefill.cpp), check_cu_syntax.sh
- crates/engine-qwen35-cuda/tests/stra161_reference/reference.py (fixtures.json and the Rust constants stay)
- control-plane/tests/golden/gen_goldens.py, scripts/offline/ (Python differentials and golden generators against the Strata Python tools)

Source-compiling CUDA oracles and builders
- scripts/build-cuda-{projection-family,q5,q6,qsa}-oracle.sh with scripts/cuda-{projection-family,q5,q6,qsa}-oracle/ (include the Original .cu; sha256 pins of them)
- scripts/build-original-verify-ptx.sh, scripts/q8/rebuild_quantizer_ptx.sh, scripts/decode-sm120/make_iq_prefix.py (needs engine/strata/include)
- scripts/cuda-stubs/ (check-cu.py and literal_diff.py need the strata headers and the Original sources; the stub headers served only them)
- tools/chain-probe/build.sh, tools/kernel-ab/{cpp,aa.sh,smoke.sh,time_smoke.sh} (the C++ comparator is built from the Strata CPU kernels; verify_manifest.py stays)
- scripts/e2e/codex/speed/verify-hc-down-kernel-microbench-vs-upstream/ (compiles the upstream kernel from the tree)

Engine builds and Python smokes that need the tree
- scripts/build-cpu.sh, scripts/build-static-cuda.sh, scripts/check-keyless-gpu.sh, scripts/test-static-cuda-profile.py (CMake of engine/strata)
- scripts/compare-real-tokenizer.py, scripts/smoke-mtp-pack.py (reads src/core/mtp.cpp and a bench manifest), scripts/prepare-keyless-routing.py and its test
- scripts/smoke-native-pack.py became scripts/native-pack-fixture.py: the synthetic GGUF fixtures the four other smokes import stay, the iq_pack.py oracle comparison goes

Gates and CI
- scripts/check-local.sh: no live Python oracle differentials, no literal_port note, no check-cu, no build-cpu, no retired test scripts
- .github/workflows/linux.yml: the keyless-cuda, static-cuda-package and hosted-cuda-package jobs (they built the engine from the tree) and their dispatch
  inputs, and the two oracle smoke steps; .github/workflows/port.yml: the Python oracle environment and the llama.cpp fetch of port-oracles
  (the sampler host shim still runs)
- limits.json and scripts/check_limits_test.py exclude third_party/strata/ instead of engine/strata/

Documentation and comments: README.md names third_party/strata and the pin; deploy/README.md marks the retired build and smoke commands; comments
in Rust, Python and Markdown that named engine/strata/... now name "Strata 41cf05a0, ..."; the gpu-bringup scratch-copy test no longer copies the
removed include directories. Stale engine/strata paths in sealed .cu, .ptx, seal-plan and MANIFEST files are left as they are (hashes may depend on the bytes).
2026-11-23 21:19:11 +01:00

298 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 `Strata 41cf05a0, 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::{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]);
}