Files
leleka/crates/native-cpu-expert/examples/kernel_ab/tests.rs
T

190 lines
6.1 KiB
Rust

//! Tests of the KAB1 reader, the comparison, the record writer, the alternation runner and the timing mode; the
//! synthetic KAB1 directories they read are built here.
use super::*;
use std::sync::atomic::{AtomicUsize, Ordering};
mod alternation;
mod reader;
mod timing;
static COUNTER: AtomicUsize = AtomicUsize::new(0);
struct TempDir(PathBuf);
impl TempDir {
fn new() -> Self {
let p = std::env::temp_dir().join(format!(
"kab1-test-{}-{}",
std::process::id(),
COUNTER.fetch_add(1, Ordering::SeqCst)
));
fs::create_dir_all(&p).unwrap();
Self(p)
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
/// The keys every COMPONENT_KERNEL record carries.
const RECORD_KEYS: [&str; 19] = [
"schema_version",
"level",
"record_id",
"created_utc",
"run_started_utc",
"machine",
"kernel",
"toolchain",
"case_id",
"input_sha256",
"kab1_manifest_sha256",
"tree",
"regime",
"pin",
"strata_upstream_commit",
"clock_calibration",
"rows",
"aa_noise_floor",
"equality",
];
/// The provenance block of the synthetic manifest.
const PROVENANCE: &str = "{\"engine_strata_pin\": \"41cf05a06a25dd29103b7b27a2279a3f60c21876\", \
\"compiler_id\": \"GNU\", \"compiler_version\": \"15.2.0\", \"target_triple\": \"x86_64-linux-gnu\", \
\"built_at_utc\": \"2026-10-28T19:05:05Z\", \"avx512_ok\": true, \"flags\": {\"strata_cxx_flags\": \
\"-O3 -DNDEBUG\", \"ggml_cpu_arch_flags\": \"-march=native\"}}";
fn assert_record_keys(rec: &Json, prefix: &str) {
for key in RECORD_KEYS {
assert!(rec.get(key).is_some(), "{prefix}{key}");
}
}
fn block_filled(len: usize, block: usize, seed: u8) -> Vec<u8> {
let mut v: Vec<u8> = (0..len).map(|i| (i as u8).wrapping_mul(31).wrapping_add(seed)).collect();
for at in (0..len).step_by(block) {
v[at] = 0x00;
v[at + 1] = 0x3c; // FP16 1.0
}
v
}
fn in_file(gu: i32, down: i32, rows: usize) -> Vec<u8> {
let (gq, gb) = (gate_up_row(gu).unwrap().2, gate_up_row(gu).unwrap().3);
let (dq, db) = (down_row(down).unwrap().2, down_row(down).unwrap().3);
let (gsize, dsize) = (H / gq * gb * FF, FF / dq * db * H);
let mut b = Vec::new();
for w in [
IN_MAGIC,
1,
gu as u32,
down as u32,
rows as u32,
H as u32,
FF as u32,
gsize as u32,
gsize as u32,
dsize as u32,
] {
b.extend_from_slice(&w.to_le_bytes());
}
b.resize(IN_HEADER, 0);
b.extend(block_filled(gsize, gb, 1));
b.extend(block_filled(gsize, gb, 2));
b.extend(block_filled(dsize, db, 3));
for i in 0..rows * H {
b.extend_from_slice(&(((i % 97) as f32 - 48.0) / 16.0).to_bits().to_le_bytes());
}
b
}
fn out_file(rows: usize, tree: u32) -> Vec<u8> {
let mut b = Vec::new();
for w in [OUT_MAGIC, 1, rows as u32, H as u32, tree] {
b.extend_from_slice(&w.to_le_bytes());
}
for i in 0..rows * H {
b.extend_from_slice(&((i as f32) * 0.25).to_bits().to_le_bytes());
}
b
}
struct Spec {
gu: i32,
down: i32,
rows: usize,
tolerance: Option<&'static str>,
}
/// The manifest entry of a case up to its input file (the output files follow).
fn case_entry(s: &Spec, id: &str, inb: &[u8]) -> String {
format!(
"{{\"id\": \"{id}\", \"gu_type\": {}, \"down_type\": {}, \"rows\": {}, \"seed\": 18446744073709551615, \
\"equality\": \"{}\", \"tolerance\": {}, \"in\": \"case-{id}.in\", \"in_sha256\": \"{}\", \"in_bytes\": {}",
s.gu,
s.down,
s.rows,
if s.tolerance.is_some() { "tolerance" } else { "bitwise" },
s.tolerance.unwrap_or("null"),
sha_hex(inb),
inb.len()
)
}
/// Writes the C++ output of every tree of a case and adds them to its manifest entry and to the file list.
fn write_outs(dir: &Path, id: &str, rows: usize, entry: &mut String, files: &mut Vec<String>) {
for (k, tree) in TREES.iter().enumerate() {
let ob = out_file(rows, k as u32);
fs::write(dir.join(format!("case-{id}.cpp-{tree}.out")), &ob).unwrap();
*entry += &format!(
", \"out_cpp_{tree}\": \"case-{id}.cpp-{tree}.out\", \"out_cpp_{tree}_sha256\": \"{}\", \
\"out_cpp_{tree}_bytes\": {}",
sha_hex(&ob),
ob.len()
);
files.push(format!(
"\"case-{id}.cpp-{tree}.out\": {{\"sha256\": \"{}\", \"bytes\": {}}}",
sha_hex(&ob),
ob.len()
));
}
}
/// Writes a case and returns its manifest entry; `mutate` edits the `.in` bytes before the manifest records their hash.
fn write_case(dir: &Path, s: &Spec, mutate: &impl Fn(&mut Vec<u8>), files: &mut Vec<String>) -> String {
let id = format!("{}-{}-r{}", s.gu, s.down, s.rows);
let mut inb = in_file(s.gu, s.down, s.rows);
mutate(&mut inb);
fs::write(dir.join(format!("case-{id}.in")), &inb).unwrap();
let mut entry = case_entry(s, &id, &inb);
files.push(format!("\"case-{id}.in\": {{\"sha256\": \"{}\", \"bytes\": {}}}", sha_hex(&inb), inb.len()));
write_outs(dir, &id, s.rows, &mut entry, files);
entry + "}"
}
/// Builds a synthetic KAB1 directory; `mutate` edits the `.in` bytes before the manifest records their hash.
fn build(dir: &Path, specs: &[Spec], mutate: impl Fn(&mut Vec<u8>)) {
let mut files = Vec::new();
let cases: Vec<String> = specs.iter().map(|s| write_case(dir, s, &mutate, &mut files)).collect();
let manifest = format!(
"{{\"format\": \"KAB1\", \"version\": 1, \"run_id\": \"synthetic\", \"writer\": \"cpp\", \
\"provenance\": {PROVENANCE}, \"cases\": [{}], \"files\": {{{}}}}}",
cases.join(", "),
files.join(", ")
);
fs::write(dir.join("manifest.json"), manifest).unwrap();
}
fn two_cases() -> Vec<Spec> {
vec![Spec { gu: 42, down: 42, rows: 2, tolerance: None }, Spec { gu: 18, down: 20, rows: 1, tolerance: None }]
}
fn one_case() -> Vec<Spec> {
vec![Spec { gu: 42, down: 42, rows: 1, tolerance: None }]
}
fn id(file: &str) -> String {
format!("case-42-42-r1.{file}")
}