Files
leleka/crates/native-cpu-expert/examples/kernel_ab.rs
T
Pavlo RatushnyiandClaude Sonnet 5.5 cf811a5185 kernel_ab example: make the file its own lint gate (deny warnings, clippy::all)
cargo clippy -- -D warnings also lints the other workspace crates (pre-existing warnings
in leleka-model-format, cuda-driver, libc-shim), so the example denies its own.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 20:45:43 +01:00

1536 lines
69 KiB
Rust

#![cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
// This file is its own lint gate: `cargo clippy -- -D warnings` also lints the other workspace crates, which carry warnings of their own.
#![deny(warnings, clippy::all)]
//! Rust half of the CPU kernel A/B, part 1 (STRA-289, S0.8b): the KAB1 reader, the comparison against the C++ reference outputs and
//! the COMPONENT_KERNEL record writer. The C++ driver (`tools/kernel-ab`, STRA-248) writes a run directory `D`; this example only
//! reads it. C++ and Rust meet through files: no FFI, no unsafe, public API of the crate only, no module in the production library.
//!
//! kernel_ab verify D the reader rule: manifest, every sha256 and length, header-derived sizes, finite
//! FP16 block headers and activations; any mismatch refuses the WHOLE directory
//! kernel_ab compare D [--out R] [--pin CPU] [--machine-role NAME] [--trees avx512,avx2]
//! verify D, run our trees in fresh processes (`run-tree`), compare with the C++
//! `.out` files (bitwise on the f32 bit patterns, or the tolerance the manifest case
//! declares with its basis), write `R/case-<id>.rust-<tree>.out` and one
//! COMPONENT_KERNEL record per case and tree to `R/records/`
//! kernel_ab run-tree D --tree T --out R [--pin CPU]
//! internal: one fresh process, one tree (T = avx512 | avx2)
//!
//! Timing is NOT here (alternation runner, regimes, clock calibration, A/A floor: STRA-318). The records written by this part carry
//! the fields the schema requires for them with the explicit NOT_MEASURED marker (see `NOT_MEASURED`), never a measurement.
//!
//! cargo run --release -p leleka-native-cpu-expert --example kernel_ab -- compare D
//! cargo test -p leleka-native-cpu-expert --example kernel_ab
use leleka_native_cpu_expert::{BorrowedExpert, BorrowedGroup, DirectCpuPool, DownFormat, GateUpFormat, PreparedJob, cpu_kernel_report, rust_topology};
use sha2::{Digest, Sha256};
use std::cell::Cell;
use std::collections::BTreeSet;
use std::fs::{self, File};
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::process::{Command, ExitCode};
use std::time::{SystemTime, UNIX_EPOCH};
const IN_MAGIC: u32 = 0x4942_414B;
const OUT_MAGIC: u32 = 0x4F42_414B;
const IN_HEADER: usize = 64;
const OUT_HEADER: usize = 20;
const H: usize = 2560;
const FF: usize = 640;
const MAX_ROWS: usize = 8;
/// Largest legitimate file of the format is about 2.7 MB; anything above this is refused before any buffer is taken.
const MAX_FILE_BYTES: u64 = 16 << 20;
const MAX_MANIFEST_BYTES: u64 = 8 << 20;
const MAX_CASES: usize = 1024;
const TOLERANCE_METRIC: &str = "max_abs_error_over_max_abs_reference";
/// Marker of every schema-required timing field this part does not measure (STRA-318 fills them): a text marker where the schema takes
/// text, the smallest positive double (`5e-324`) where it takes a positive number, 1 where it takes a positive count.
const NOT_MEASURED: &str = "NOT_MEASURED (filled by STRA-318, the alternation runner)";
const TREES: [&str; 2] = ["avx512", "avx2"];
thread_local! { static BUFFERS: Cell<usize> = const { Cell::new(0) }; }
// ------------------------------------------------------------------------------------------------ formats
/// (ggml id, format, block elements, block bytes, name) as `lib.rs kind()/block()`.
const GATE_UP: [(i32, GateUpFormat, usize, usize, &str); 5] = [
(18, GateUpFormat::Iq3Xxs, 256, 98, "IQ3_XXS"),
(21, GateUpFormat::Iq3S, 256, 110, "IQ3_S"),
(22, GateUpFormat::Iq2S, 256, 82, "IQ2_S"),
(23, GateUpFormat::Iq4Xs, 256, 136, "IQ4_XS"),
(42, GateUpFormat::Q2_0, 64, 18, "Q2_0"),
];
const DOWN: [(i32, DownFormat, usize, usize, &str); 2] = [(20, DownFormat::Iq4Nl, 32, 18, "IQ4_NL"), (42, DownFormat::Q2_0, 64, 18, "Q2_0")];
fn gate_up_row(id: i32) -> Option<&'static (i32, GateUpFormat, usize, usize, &'static str)> {
GATE_UP.iter().find(|r| r.0 == id)
}
fn down_row(id: i32) -> Option<&'static (i32, DownFormat, usize, usize, &'static str)> {
DOWN.iter().find(|r| r.0 == id)
}
// ------------------------------------------------------------------------------------------------ errors
/// A refusal of the whole directory: names the file and says why. `incomplete` is the missing-manifest case.
#[derive(Debug)]
struct Refusal {
file: String,
reason: String,
incomplete: bool,
}
impl Refusal {
fn new(file: &str, reason: impl Into<String>) -> Self {
Self { file: file.to_owned(), reason: reason.into(), incomplete: false }
}
}
impl std::fmt::Display for Refusal {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if self.incomplete { write!(f, "incomplete directory: {}: {}", self.file, self.reason) } else { write!(f, "REFUSED {}: {}", self.file, self.reason) }
}
}
// ------------------------------------------------------------------------------------------------ helpers
fn sha_hex(bytes: &[u8]) -> String {
let digest = Sha256::digest(bytes);
digest.iter().map(|b| format!("{b:02x}")).collect()
}
/// The only place a buffer is taken from a length that came from a file; every caller validates the length first.
fn take_buffer(len: usize) -> Result<Vec<u8>, String> {
BUFFERS.with(|c| c.set(c.get() + 1));
let mut v = Vec::new();
v.try_reserve_exact(len).map_err(|_| format!("a buffer of {len} bytes was refused"))?;
v.resize(len, 0);
Ok(v)
}
/// Little-endian words of a byte slice (a trailing partial word is ignored; callers pass exact multiples).
fn words_le(bytes: &[u8]) -> Vec<u32> {
bytes.as_chunks::<4>().0.iter().map(|c| u32::from_le_bytes(*c)).collect()
}
fn le32(b: &[u8], at: usize) -> u32 {
u32::from_le_bytes([b[at], b[at + 1], b[at + 2], b[at + 3]])
}
fn civil_from_days(z: i64) -> (i64, u32, u32) {
let z = z + 719_468;
let era = z.div_euclid(146_097);
let doe = z.rem_euclid(146_097);
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let y = yoe + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
(if m <= 2 { y + 1 } else { y }, m, d)
}
fn utc_of(secs: u64) -> String {
let (y, m, d) = civil_from_days((secs / 86_400) as i64);
let s = secs % 86_400;
format!("{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z", s / 3600, s % 3600 / 60, s % 60)
}
fn now_utc() -> String {
utc_of(SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_secs()))
}
fn is_utc(s: &str) -> bool {
let b = s.as_bytes();
b.len() == 20 && b.iter().enumerate().all(|(i, c)| match i {
4 | 7 => *c == b'-',
10 => *c == b'T',
13 | 16 => *c == b':',
19 => *c == b'Z',
_ => c.is_ascii_digit(),
})
}
fn is_hex(s: &str, min: usize, max: usize) -> bool {
(min..=max).contains(&s.len()) && s.bytes().all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c))
}
fn valid_id(id: &str) -> bool {
!id.is_empty() && id.len() <= 64 && id.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'-' || c == b'_')
}
// ------------------------------------------------------------------------------------------------ JSON (read)
#[derive(Debug, Clone, PartialEq)]
enum Json {
Null,
Bool(bool),
Num(String),
Str(String),
Arr(Vec<Json>),
Obj(Vec<(String, Json)>),
}
struct Parser<'a> {
b: &'a [u8],
at: usize,
}
impl Parser<'_> {
fn ws(&mut self) {
while self.at < self.b.len() && matches!(self.b[self.at], b' ' | b'\t' | b'\n' | b'\r') {
self.at += 1;
}
}
fn err<T>(&self, what: &str) -> Result<T, String> {
Err(format!("JSON error at byte {}: {what}", self.at))
}
fn lit(&mut self, word: &str, v: Json) -> Result<Json, String> {
if self.b[self.at..].starts_with(word.as_bytes()) {
self.at += word.len();
Ok(v)
} else {
self.err("unknown literal")
}
}
fn hex4(&mut self) -> Result<u32, String> {
if self.at + 4 > self.b.len() {
return self.err("short \\u escape");
}
let s = std::str::from_utf8(&self.b[self.at..self.at + 4]).map_err(|_| "bad \\u escape".to_owned())?;
let v = u32::from_str_radix(s, 16).map_err(|_| "bad \\u escape".to_owned())?;
self.at += 4;
Ok(v)
}
fn string(&mut self) -> Result<String, String> {
self.at += 1;
let mut out: Vec<u8> = Vec::new();
loop {
let Some(&c) = self.b.get(self.at) else { return self.err("unterminated string") };
self.at += 1;
match c {
b'"' => return String::from_utf8(out).map_err(|_| "string is not UTF-8".to_owned()),
b'\\' => {
let Some(&e) = self.b.get(self.at) else { return self.err("unterminated escape") };
self.at += 1;
let ch = match e {
b'"' => '"',
b'\\' => '\\',
b'/' => '/',
b'b' => '\u{8}',
b'f' => '\u{c}',
b'n' => '\n',
b'r' => '\r',
b't' => '\t',
b'u' => {
let hi = self.hex4()?;
let cp = if (0xD800..0xDC00).contains(&hi) {
if !self.b[self.at..].starts_with(b"\\u") {
return self.err("lone surrogate");
}
self.at += 2;
let lo = self.hex4()?;
if !(0xDC00..0xE000).contains(&lo) {
return self.err("lone surrogate");
}
0x10000 + ((hi - 0xD800) << 10) + (lo - 0xDC00)
} else {
hi
};
match char::from_u32(cp) {
Some(c) => c,
None => return self.err("lone surrogate"),
}
}
_ => return self.err("unknown escape"),
};
let mut buf = [0u8; 4];
out.extend_from_slice(ch.encode_utf8(&mut buf).as_bytes());
}
0..=0x1f => return self.err("control character in string"),
_ => out.push(c),
}
}
}
fn number(&mut self) -> Result<Json, String> {
let start = self.at;
while self.at < self.b.len() && matches!(self.b[self.at], b'-' | b'+' | b'.' | b'e' | b'E' | b'0'..=b'9') {
self.at += 1;
}
let text = std::str::from_utf8(&self.b[start..self.at]).map_err(|_| "bad number".to_owned())?;
if text.parse::<f64>().is_err() {
return self.err("bad number");
}
Ok(Json::Num(text.to_owned()))
}
fn value(&mut self, depth: usize) -> Result<Json, String> {
if depth > 32 {
return self.err("nesting deeper than 32");
}
self.ws();
match self.b.get(self.at) {
None => self.err("unexpected end"),
Some(b'{') => {
self.at += 1;
let mut items: Vec<(String, Json)> = Vec::new();
self.ws();
if self.b.get(self.at) == Some(&b'}') {
self.at += 1;
return Ok(Json::Obj(items));
}
loop {
self.ws();
if self.b.get(self.at) != Some(&b'"') {
return self.err("object key expected");
}
let key = self.string()?;
if items.iter().any(|(k, _)| *k == key) {
return self.err(&format!("duplicate key {key:?}"));
}
self.ws();
if self.b.get(self.at) != Some(&b':') {
return self.err("':' expected");
}
self.at += 1;
let v = self.value(depth + 1)?;
items.push((key, v));
self.ws();
match self.b.get(self.at) {
Some(b',') => self.at += 1,
Some(b'}') => {
self.at += 1;
return Ok(Json::Obj(items));
}
_ => return self.err("',' or '}' expected"),
}
}
}
Some(b'[') => {
self.at += 1;
let mut items = Vec::new();
self.ws();
if self.b.get(self.at) == Some(&b']') {
self.at += 1;
return Ok(Json::Arr(items));
}
loop {
items.push(self.value(depth + 1)?);
self.ws();
match self.b.get(self.at) {
Some(b',') => self.at += 1,
Some(b']') => {
self.at += 1;
return Ok(Json::Arr(items));
}
_ => return self.err("',' or ']' expected"),
}
}
}
Some(b'"') => Ok(Json::Str(self.string()?)),
Some(b't') => self.lit("true", Json::Bool(true)),
Some(b'f') => self.lit("false", Json::Bool(false)),
Some(b'n') => self.lit("null", Json::Null),
Some(b'-' | b'0'..=b'9') => self.number(),
Some(_) => self.err("unexpected character"),
}
}
}
fn parse_json(bytes: &[u8]) -> Result<Json, String> {
let mut p = Parser { b: bytes, at: 0 };
let v = p.value(0)?;
p.ws();
if p.at != bytes.len() {
return p.err("trailing data");
}
Ok(v)
}
impl Json {
fn get(&self, key: &str) -> Option<&Json> {
match self {
Json::Obj(items) => items.iter().find(|(k, _)| k == key).map(|(_, v)| v),
_ => None,
}
}
fn req(&self, key: &str) -> Result<&Json, String> {
self.get(key).ok_or_else(|| format!("missing key {key:?}"))
}
fn str(&self, key: &str) -> Result<&str, String> {
match self.req(key)? {
Json::Str(s) => Ok(s),
_ => Err(format!("key {key:?} is not a string")),
}
}
fn uint(&self, key: &str) -> Result<u64, String> {
match self.req(key)? {
Json::Num(n) => n.parse::<u64>().map_err(|_| format!("key {key:?} is not an unsigned integer")),
_ => Err(format!("key {key:?} is not a number")),
}
}
}
// ------------------------------------------------------------------------------------------------ KAB1 headers
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct InHeader {
gu: i32,
down: i32,
rows: usize,
gate: usize,
up: usize,
down_bytes: usize,
}
impl InHeader {
fn input_at(&self) -> usize {
IN_HEADER + self.gate + self.up + self.down_bytes
}
}
/// Pure: decides from 64 header bytes and the file length, allocates nothing.
fn validate_in_header(h: &[u8; IN_HEADER], file_len: u64) -> Result<InHeader, String> {
if le32(h, 0) != IN_MAGIC {
return Err(format!("wrong magic 0x{:08x}, expected 0x{IN_MAGIC:08x}", le32(h, 0)));
}
if le32(h, 4) != 1 {
return Err(format!("unsupported version {}, expected 1", le32(h, 4)));
}
let (gu, down) = (le32(h, 8) as i32, le32(h, 12) as i32);
let Some(&(_, _, gq, gb, _)) = gate_up_row(gu) else { return Err(format!("gate/up type {gu} is not in the KAB1 list")) };
let Some(&(_, _, dq, db, _)) = down_row(down) else { return Err(format!("down type {down} is not in the KAB1 list")) };
let rows = le32(h, 16) as usize;
if !(1..=MAX_ROWS).contains(&rows) {
return Err(format!("rows {rows} outside 1..={MAX_ROWS}"));
}
if le32(h, 20) as usize != H || le32(h, 24) as usize != FF {
return Err(format!("n_embd {} / n_ff {} differ from {H} / {FF}", le32(h, 20), le32(h, 24)));
}
let gsize = (H / gq * gb * FF) as u64;
let dsize = (FF / dq * db * H) as u64;
let (g, u, d) = (le32(h, 28) as u64, le32(h, 32) as u64, le32(h, 36) as u64);
if g != gsize || u != gsize || d != dsize {
return Err(format!("byte counts gate/up/down {g}/{u}/{d} differ from the format-derived {gsize}/{gsize}/{dsize}"));
}
if h[40..].iter().any(|b| *b != 0) {
return Err("header padding is not zero".to_owned());
}
let total = IN_HEADER as u64 + g + u + d + (rows * H * 4) as u64;
if total != file_len {
return Err(format!("file length {file_len} differs from the header-derived {total}"));
}
Ok(InHeader { gu, down, rows, gate: g as usize, up: u as usize, down_bytes: d as usize })
}
/// Pure: 20 bytes and the file length.
fn validate_out_header(h: &[u8; OUT_HEADER], file_len: u64, rows: usize, tree: &str) -> Result<(), String> {
if le32(h, 0) != OUT_MAGIC {
return Err(format!("wrong magic 0x{:08x}, expected 0x{OUT_MAGIC:08x}", le32(h, 0)));
}
if le32(h, 4) != 1 {
return Err(format!("unsupported version {}, expected 1", le32(h, 4)));
}
if le32(h, 8) as usize != rows || le32(h, 12) as usize != H {
return Err(format!("rows {} / n_embd {} differ from the case ({rows} / {H})", le32(h, 8), le32(h, 12)));
}
let tree_id = TREES.iter().position(|t| *t == tree).map_or(u32::MAX, |i| i as u32);
if le32(h, 16) != tree_id {
return Err(format!("tree id {} differs from the file name's tree {tree} ({tree_id})", le32(h, 16)));
}
let total = (OUT_HEADER + rows * H * 4) as u64;
if total != file_len {
return Err(format!("file length {file_len} differs from the header-derived {total}"));
}
Ok(())
}
fn fp16_finite(bytes: &[u8], block: usize) -> Option<usize> {
(0..bytes.len()).step_by(block).find(|&at| u16::from_le_bytes([bytes[at], bytes[at + 1]]) & 0x7c00 == 0x7c00)
}
// ------------------------------------------------------------------------------------------------ manifest
#[derive(Debug, Clone, PartialEq)]
struct Tolerance {
value: f64,
basis: String,
basis_written_utc: String,
}
#[derive(Debug, Clone)]
struct OutRef {
tree: &'static str,
name: String,
sha256: String,
bytes: u64,
}
#[derive(Debug, Clone)]
struct CaseEntry {
id: String,
gu: i32,
down: i32,
rows: usize,
in_name: String,
in_sha256: String,
in_bytes: u64,
outs: Vec<OutRef>,
tolerance: Option<Tolerance>,
}
#[derive(Debug, Clone)]
struct Provenance {
run_id: String,
engine_strata_pin: String,
compiler_id: String,
compiler_version: String,
target_triple: String,
reference_flags: String,
avx512_ok: Option<bool>,
}
#[derive(Debug)]
struct Verified {
dir: PathBuf,
manifest_sha256: String,
provenance: Provenance,
cases: Vec<CaseEntry>,
file_count: usize,
}
type FileTable = Vec<(String, String, u64)>;
fn parse_manifest(m: &Json) -> Result<(Provenance, Vec<CaseEntry>, FileTable), String> {
if m.str("format")? != "KAB1" || m.uint("version")? != 1 {
return Err("format is not KAB1 version 1".to_owned());
}
let p = m.req("provenance")?;
let flags = p.req("flags")?;
let commit = p.str("engine_strata_pin")?;
if !is_hex(commit, 7, 40) {
return Err("provenance.engine_strata_pin is not a commit hash".to_owned());
}
let built = p.str("built_at_utc")?;
if !is_utc(built) {
return Err("provenance.built_at_utc is not a UTC timestamp".to_owned());
}
let avx512_ok = match p.get("avx512_ok") {
Some(Json::Bool(b)) => Some(*b),
_ => None,
};
let provenance = Provenance {
run_id: m.str("run_id")?.to_owned(),
engine_strata_pin: commit.to_owned(),
compiler_id: p.str("compiler_id")?.to_owned(),
compiler_version: p.str("compiler_version")?.to_owned(),
target_triple: p.str("target_triple")?.to_owned(),
reference_flags: format!("strata_cxx_flags: {}; ggml_cpu_arch_flags: {}", flags.str("strata_cxx_flags")?, flags.str("ggml_cpu_arch_flags")?),
avx512_ok,
};
let Json::Arr(cases_json) = m.req("cases")? else { return Err("cases is not an array".to_owned()) };
if cases_json.is_empty() || cases_json.len() > MAX_CASES {
return Err(format!("{} cases (1..={MAX_CASES} allowed)", cases_json.len()));
}
let mut cases = Vec::new();
for c in cases_json {
let id = c.str("id")?.to_owned();
if !valid_id(&id) {
return Err(format!("case id {id:?} is not a plain identifier"));
}
let rows = c.uint("rows")? as usize;
let in_name = format!("case-{id}.in");
if c.str("in")? != in_name {
return Err(format!("case {id}: file name {:?} is not {in_name}", c.str("in")?));
}
let mut outs = Vec::new();
for tree in TREES {
let key = format!("out_cpp_{tree}");
let name = format!("case-{id}.cpp-{tree}.out");
if c.str(&key)? != name {
return Err(format!("case {id}: file name {:?} is not {name}", c.str(&key)?));
}
outs.push(OutRef { tree, name, sha256: c.str(&format!("{key}_sha256"))?.to_owned(), bytes: c.uint(&format!("{key}_bytes"))? });
}
let tolerance = match (c.str("equality")?, c.req("tolerance")?) {
("bitwise", Json::Null) => None,
("tolerance", t @ Json::Obj(_)) => {
if t.str("metric")? != TOLERANCE_METRIC {
return Err(format!("case {id}: tolerance metric {:?} is not {TOLERANCE_METRIC}", t.str("metric")?));
}
let value = match t.req("value")? {
Json::Num(n) => n.parse::<f64>().ok().filter(|v| v.is_finite() && *v > 0.0),
_ => None,
}
.ok_or_else(|| format!("case {id}: tolerance.value is not a positive number"))?;
let basis = t.str("basis")?.to_owned();
let written = t.str("basis_written_utc")?.to_owned();
if basis.trim().is_empty() || !is_utc(&written) {
return Err(format!("case {id}: tolerance needs a non-empty basis and a UTC basis_written_utc"));
}
if written.as_str() > built {
return Err(format!("case {id}: the tolerance basis was written {written}, after the reference run {built}"));
}
Some(Tolerance { value, basis, basis_written_utc: written })
}
(other, _) => return Err(format!("case {id}: equality {other:?} and tolerance disagree (bitwise needs null, tolerance an object)")),
};
let in_sha256 = c.str("in_sha256")?.to_owned();
let gu = c.uint("gu_type")? as i32;
let down = c.uint("down_type")? as i32;
cases.push(CaseEntry { id, gu, down, rows, in_name, in_sha256, in_bytes: c.uint("in_bytes")?, outs, tolerance });
}
let Json::Obj(files_json) = m.req("files")? else { return Err("files is not an object".to_owned()) };
let mut files = Vec::new();
for (name, v) in files_json {
let sha = v.str("sha256")?;
if !is_hex(sha, 64, 64) {
return Err(format!("files.{name}.sha256 is not a sha256"));
}
files.push((name.clone(), sha.to_owned(), v.uint("bytes")?));
}
let mut seen = BTreeSet::new();
for c in &cases {
if !seen.insert(c.id.clone()) {
return Err(format!("case id {} appears twice", c.id));
}
for sha in std::iter::once(&c.in_sha256).chain(c.outs.iter().map(|o| &o.sha256)) {
if !is_hex(sha, 64, 64) {
return Err(format!("case {}: a sha256 is not 64 lowercase hex digits", c.id));
}
}
}
Ok((provenance, cases, files))
}
fn case_files(c: &CaseEntry) -> Vec<(&str, &str, u64)> {
let mut v = vec![(c.in_name.as_str(), c.in_sha256.as_str(), c.in_bytes)];
v.extend(c.outs.iter().map(|o| (o.name.as_str(), o.sha256.as_str(), o.bytes)));
v
}
// ------------------------------------------------------------------------------------------------ file readers
#[derive(Debug)]
struct CaseIn {
header: InHeader,
blob: Vec<u8>,
}
impl CaseIn {
fn gate(&self) -> &[u8] {
&self.blob[IN_HEADER..IN_HEADER + self.header.gate]
}
fn up(&self) -> &[u8] {
let s = IN_HEADER + self.header.gate;
&self.blob[s..s + self.header.up]
}
fn down(&self) -> &[u8] {
let s = IN_HEADER + self.header.gate + self.header.up;
&self.blob[s..s + self.header.down_bytes]
}
fn input(&self) -> Vec<f32> {
words_le(&self.blob[self.header.input_at()..]).into_iter().map(f32::from_bits).collect()
}
}
/// Reads one case input: length against the manifest and the limit, header decision, THEN the buffer, then sha256, FP16 headers and
/// finite activations. Any failure names the file.
fn read_case_in(dir: &Path, c: &CaseEntry) -> Result<CaseIn, Refusal> {
let name = c.in_name.as_str();
let r = |reason: String| Refusal::new(name, reason);
let mut f = File::open(dir.join(name)).map_err(|e| r(format!("cannot open: {e}")))?;
let len = f.metadata().map_err(|e| r(format!("cannot stat: {e}")))?.len();
if len != c.in_bytes {
return Err(r(format!("length {len} differs from the manifest's {}", c.in_bytes)));
}
if len > MAX_FILE_BYTES || len < IN_HEADER as u64 {
return Err(r(format!("length {len} outside {IN_HEADER}..={MAX_FILE_BYTES}")));
}
let mut hdr = [0u8; IN_HEADER];
f.read_exact(&mut hdr).map_err(|e| r(format!("cannot read the header: {e}")))?;
let header = validate_in_header(&hdr, len).map_err(r)?;
if header.gu != c.gu || header.down != c.down || header.rows != c.rows {
return Err(r("the header's types / rows differ from the manifest case".to_owned()));
}
let mut blob = take_buffer(len as usize).map_err(r)?;
blob[..IN_HEADER].copy_from_slice(&hdr);
f.read_exact(&mut blob[IN_HEADER..]).map_err(|e| r(format!("cannot read the body: {e}")))?;
if sha_hex(&blob) != c.in_sha256 {
return Err(r("sha256 differs from the manifest".to_owned()));
}
let case = CaseIn { header, blob };
let (gb, db) = (gate_up_row(header.gu).map_or(1, |x| x.3), down_row(header.down).map_or(1, |x| x.3));
for (role, bytes, block) in [("gate", case.gate(), gb), ("up", case.up(), gb), ("down", case.down(), db)] {
if let Some(at) = fp16_finite(bytes, block) {
return Err(r(format!("non-finite FP16 block header in {role} at byte {at}")));
}
}
if words_le(&case.blob[header.input_at()..]).into_iter().any(|w| !f32::from_bits(w).is_finite()) {
return Err(r("non-finite activation".to_owned()));
}
Ok(case)
}
/// Reads an `.out` file as f32 bit patterns. `expect` is the manifest's (sha256, bytes) for a C++ file; ours has none.
fn read_out(path: &Path, name: &str, rows: usize, tree: &str, expect: Option<(&str, u64)>) -> Result<Vec<u32>, Refusal> {
let r = |reason: String| Refusal::new(name, reason);
let mut f = File::open(path).map_err(|e| r(format!("cannot open: {e}")))?;
let len = f.metadata().map_err(|e| r(format!("cannot stat: {e}")))?.len();
if let Some((_, bytes)) = expect
&& len != bytes
{
return Err(r(format!("length {len} differs from the manifest's {bytes}")));
}
if len > MAX_FILE_BYTES || len < OUT_HEADER as u64 {
return Err(r(format!("length {len} outside {OUT_HEADER}..={MAX_FILE_BYTES}")));
}
let mut hdr = [0u8; OUT_HEADER];
f.read_exact(&mut hdr).map_err(|e| r(format!("cannot read the header: {e}")))?;
validate_out_header(&hdr, len, rows, tree).map_err(r)?;
let mut blob = take_buffer(len as usize).map_err(r)?;
blob[..OUT_HEADER].copy_from_slice(&hdr);
f.read_exact(&mut blob[OUT_HEADER..]).map_err(|e| r(format!("cannot read the body: {e}")))?;
if let Some((sha, _)) = expect
&& sha_hex(&blob) != sha
{
return Err(r("sha256 differs from the manifest".to_owned()));
}
let bits = words_le(&blob[OUT_HEADER..]);
if bits.iter().any(|b| !f32::from_bits(*b).is_finite()) {
return Err(r("non-finite value".to_owned()));
}
Ok(bits)
}
/// The reader rule. Everything in the directory is checked before anything is used; any problem refuses the whole directory.
fn verify_dir(dir: &Path) -> Result<Verified, Refusal> {
let mpath = dir.join("manifest.json");
let mname = "manifest.json";
if !mpath.is_file() {
let mut r = Refusal::new(mname, "no manifest.json (the writer publishes it last)");
r.incomplete = true;
return Err(r);
}
let r = |reason: String| Refusal::new(mname, reason);
let mut f = File::open(&mpath).map_err(|e| r(format!("cannot open: {e}")))?;
let mlen = f.metadata().map_err(|e| r(format!("cannot stat: {e}")))?.len();
if mlen > MAX_MANIFEST_BYTES {
return Err(r(format!("length {mlen} above the limit {MAX_MANIFEST_BYTES}")));
}
let mut mbytes = take_buffer(mlen as usize).map_err(r)?;
f.read_exact(&mut mbytes).map_err(|e| r(format!("cannot read: {e}")))?;
let manifest = parse_json(&mbytes).map_err(r)?;
let (provenance, cases, files) = parse_manifest(&manifest).map_err(r)?;
// the flat files table and the case entries must describe exactly the same files
let mut expected: Vec<(&str, &str, u64)> = cases.iter().flat_map(case_files).collect();
expected.sort_unstable();
let mut table: Vec<(&str, &str, u64)> = files.iter().map(|(n, s, b)| (n.as_str(), s.as_str(), *b)).collect();
table.sort_unstable();
if expected != table {
return Err(r("the flat files table and the case entries disagree".to_owned()));
}
let names: BTreeSet<&str> = expected.iter().map(|e| e.0).collect();
let listing = fs::read_dir(dir).map_err(|e| r(format!("cannot list the directory: {e}")))?;
for entry in listing {
let entry = entry.map_err(|e| r(format!("cannot list the directory: {e}")))?;
let n = entry.file_name().to_string_lossy().into_owned();
if n != mname && !names.contains(n.as_str()) {
return Err(Refusal::new(&n, "file is not in the manifest"));
}
}
let file_count = names.len() + 1;
for c in &cases {
read_case_in(dir, c)?;
for o in &c.outs {
read_out(&dir.join(&o.name), &o.name, c.rows, o.tree, Some((&o.sha256, o.bytes)))?;
}
}
Ok(Verified { dir: dir.to_owned(), manifest_sha256: sha_hex(&mbytes), provenance, cases, file_count })
}
// ------------------------------------------------------------------------------------------------ compare
#[derive(Debug, PartialEq)]
struct Outcome {
compared: usize,
mismatches: usize,
differing_bits: usize,
max_abs_error: f64,
first_mismatch: Option<(usize, u32, u32)>,
}
impl Outcome {
fn equal(&self) -> bool {
self.mismatches == 0
}
}
/// Bitwise on the f32 bit patterns (so -0 and +0 differ) when `tol` is None; otherwise `|ours - ref| <= value * max|ref|` per value
/// (the one metric the reader knows, `TOLERANCE_METRIC`).
fn compare_bits(ours: &[u32], reference: &[u32], tol: Option<&Tolerance>) -> Outcome {
let scale = reference.iter().map(|b| f64::from(f32::from_bits(*b)).abs()).fold(0.0, f64::max);
let mut o = Outcome { compared: reference.len(), mismatches: 0, differing_bits: 0, max_abs_error: 0.0, first_mismatch: None };
for (i, (a, b)) in ours.iter().zip(reference).enumerate() {
let err = (f64::from(f32::from_bits(*a)) - f64::from(f32::from_bits(*b))).abs();
if a != b {
o.differing_bits += 1;
}
if err.is_finite() {
o.max_abs_error = o.max_abs_error.max(err);
}
let bad = match tol {
None => a != b,
Some(t) => err.partial_cmp(&(t.value * scale)).is_none_or(|o| o == std::cmp::Ordering::Greater),
};
if bad {
o.mismatches += 1;
o.first_mismatch.get_or_insert((i, *a, *b));
}
}
if ours.len() != reference.len() {
o.mismatches += ours.len().abs_diff(reference.len());
}
o
}
// ------------------------------------------------------------------------------------------------ record (hand-written JSON)
fn jstr(s: &str) -> String {
let mut o = String::with_capacity(s.len() + 2);
o.push('"');
for c in s.chars() {
match c {
'"' => o.push_str("\\\""),
'\\' => o.push_str("\\\\"),
'\n' => o.push_str("\\n"),
'\r' => o.push_str("\\r"),
'\t' => o.push_str("\\t"),
c if (c as u32) < 0x20 => o.push_str(&format!("\\u{:04x}", c as u32)),
c => o.push(c),
}
}
o.push('"');
o
}
struct RecordInput<'a> {
record_id: String,
created_utc: String,
run_started_utc: String,
machine_role: String,
cpu_model: String,
os: String,
ours_compiler: String,
ours_version: String,
ours_triple: String,
ours_flags: String,
tree: &'a str,
verified: &'a Verified,
case: &'a CaseEntry,
pin_cpu: usize,
sibling_idle: bool,
outcome: &'a Outcome,
}
fn record_json(r: &RecordInput) -> String {
let p = &r.verified.provenance;
let c = r.case;
let mode = if c.tolerance.is_some() { "tolerance" } else { "bitwise" };
let tolerance = c.tolerance.as_ref().map_or(String::new(), |t| {
format!(
",\n \"tolerance\": {{\"value\": {:e}, \"basis\": {}, \"basis_written_utc\": {}}}",
t.value,
jstr(&format!("{} [metric: {TOLERANCE_METRIC}]", t.basis)),
jstr(&t.basis_written_utc)
)
});
let tiny = format!("{:e}", f64::from_bits(1));
let (gu, down) = (gate_up_row(c.gu).map_or("?", |x| x.4), down_row(c.down).map_or("?", |x| x.4));
format!(
"{{\n \"schema_version\": \"1\",\n \"level\": \"COMPONENT_KERNEL\",\n \"record_id\": {rid},\n \"created_utc\": {created},\n \"run_started_utc\": {started},\n \"machine\": {{\"machine_role\": {role}, \"cpu_model\": {cpu}, \"gpu_name\": \"none\", \"os\": {os}}},\n \"kernel\": {kernel},\n \"toolchain\": {{\n \"ours\": {{\"compiler\": {oc}, \"version\": {ov}, \"target_triple\": {ot}, \"flags\": {of}}},\n \"reference\": {{\"compiler\": {rc}, \"version\": {rv}, \"target_triple\": {rt}, \"flags\": {rf}}}\n }},\n \"case_id\": {cid},\n \"input_sha256\": {insha},\n \"kab1_manifest_sha256\": {msha},\n \"tree\": {{\"ours\": {tree}, \"reference\": {tree}}},\n \"regime\": \"resident\",\n \"pin\": {{\"logical_cpu\": {pin}, \"sibling_idle\": {sib}}},\n \"strata_upstream_commit\": {commit},\n \"clock_calibration\": {{\"method\": {nm}, \"ghz_before\": {tiny}, \"ghz_after\": {tiny}, \"max_drift_fraction\": 0, \"slices_total\": 1, \"slices_dropped\": 0}},\n \"rows\": [\n {{\"row_type\": {rowtype}, \"unit\": \"ns\", \"rounds\": 1, \"ours\": {{\"median\": {tiny}, \"p05\": {tiny}, \"p95\": {tiny}}}, \"reference\": {{\"median\": {tiny}, \"p05\": {tiny}, \"p95\": {tiny}}}}}\n ],\n \"aa_noise_floor\": {{\"ours_vs_ours\": {{\"n\": 1, \"ci95_low\": 0, \"ci95_high\": 0}}, \"reference_vs_reference\": {{\"n\": 1, \"ci95_low\": 0, \"ci95_high\": 0}}, \"floor_fraction\": 0}},\n \"equality\": {{\n \"mode\": \"{mode}\",\n \"verdict\": \"{verdict}\",\n \"compared_values\": {compared},\n \"mismatches\": {mism}{tolerance}\n }}\n}}\n",
rid = jstr(&r.record_id),
created = jstr(&r.created_utc),
started = jstr(&r.run_started_utc),
role = jstr(&r.machine_role),
cpu = jstr(&r.cpu_model),
os = jstr(&r.os),
kernel = jstr(&format!("routed-expert-gate-up-down {gu}+{down} rows={} (equality only; timing {NOT_MEASURED})", c.rows)),
oc = jstr(&r.ours_compiler),
ov = jstr(&r.ours_version),
ot = jstr(&r.ours_triple),
of = jstr(&r.ours_flags),
rc = jstr(&p.compiler_id),
rv = jstr(&p.compiler_version),
rt = jstr(&p.target_triple),
rf = jstr(&p.reference_flags),
cid = jstr(&c.id),
insha = jstr(&c.in_sha256),
msha = jstr(&r.verified.manifest_sha256),
tree = jstr(r.tree),
pin = r.pin_cpu,
sib = r.sibling_idle,
commit = jstr(&p.engine_strata_pin),
nm = jstr(NOT_MEASURED),
rowtype = jstr(&format!("{gu}+{down} r{} {NOT_MEASURED}", c.rows)),
verdict = if r.outcome.equal() { "EQUAL" } else { "NOT_EQUAL" },
compared = r.outcome.compared,
mism = r.outcome.mismatches,
)
}
// ------------------------------------------------------------------------------------------------ run-tree (one fresh process)
fn write_out(path: &Path, rows: usize, tree: &str, values: &[f32]) -> Result<(), String> {
let tree_id = TREES.iter().position(|t| *t == tree).ok_or("unknown tree")? as u32;
let mut b = Vec::with_capacity(OUT_HEADER + values.len() * 4);
for w in [OUT_MAGIC, 1, rows as u32, H as u32, tree_id] {
b.extend_from_slice(&w.to_le_bytes());
}
for v in values {
b.extend_from_slice(&v.to_bits().to_le_bytes());
}
File::create(path).and_then(|mut f| f.write_all(&b)).map_err(|e| format!("{}: {e}", path.display()))
}
/// Our kernels on one verified case through the public API: PreparedJob only for the input validation it performs, then one
/// `compute_group` over borrowed bytes (one expert, `rows` tokens, pairs `(t, 0)`, stride 1).
fn compute_case(pool: &mut DirectCpuPool, case: &CaseIn) -> Result<Vec<f32>, String> {
let (gu, down) = (gate_up_row(case.header.gu).ok_or("gate/up type")?.1, down_row(case.header.down).ok_or("down type")?.1);
let input = case.input();
PreparedJob::new(gu, down, case.gate().into(), case.up().into(), case.down().into(), input.clone().into(), case.header.rows)
.map_err(|e| format!("PreparedJob refused the input: {e:?}"))?;
let pairs: Vec<(usize, usize)> = (0..case.header.rows).map(|t| (t, 0)).collect();
let expert = BorrowedExpert { gate: case.gate(), up: case.up(), down: case.down(), pairs: &pairs };
let experts = [expert];
let group = BorrowedGroup { tokens: &input, experts: &experts, stride: 1 };
let mut out = vec![0.0f32; case.header.rows * H];
pool.compute_group(gu, down, &group, &mut out).map_err(|e| format!("compute_group failed: {e:?}"))?;
Ok(out)
}
fn family_of(report: &[String]) -> Option<&'static str> {
report.iter().find(|l| l.starts_with("cpu: process kernel family ")).map(|l| if l.starts_with("cpu: process kernel family AVX-512") { "avx512" } else { "avx2" })
}
fn cmd_run_tree(dir: &Path, tree: &str, out: &Path, pin: usize) -> Result<ExitCode, String> {
let verified = verify_dir(dir).map_err(|e| e.to_string())?;
let previous = rust_topology::pin_current_thread(pin as i32);
if previous < 0 {
eprintln!("kernel_ab: the pin to CPU {pin} was refused; running unpinned");
}
let report = cpu_kernel_report();
for line in &report {
println!("REPORT {line}");
}
let family = family_of(&report).ok_or("no process kernel family line in cpu_kernel_report")?;
if family != tree {
eprintln!("kernel_ab: this process runs the {family} family, not {tree}");
return Ok(ExitCode::from(3));
}
fs::create_dir_all(out).map_err(|e| format!("{}: {e}", out.display()))?;
let mut pool = DirectCpuPool::new(1).map_err(|e| format!("DirectCpuPool::new(1) failed: {e:?}"))?;
for c in &verified.cases {
let case = read_case_in(&verified.dir, c).map_err(|e| e.to_string())?;
let values = compute_case(&mut pool, &case).map_err(|e| format!("case {}: {e}", c.id))?;
write_out(&out.join(format!("case-{}.rust-{tree}.out", c.id)), c.rows, tree, &values)?;
}
println!("RUN-TREE {tree} cases={}", verified.cases.len());
Ok(ExitCode::SUCCESS)
}
// ------------------------------------------------------------------------------------------------ compare driver
/// Linux: is the SMT sibling of `cpu` idle (below 5 percent busy over 200 ms)? No sibling counts as idle. Elsewhere: false (unknown).
fn sibling_idle(cpu: usize) -> bool {
if !cfg!(target_os = "linux") {
return false;
}
let Ok(list) = fs::read_to_string(format!("/sys/devices/system/cpu/cpu{cpu}/topology/thread_siblings_list")) else { return false };
let mut siblings = Vec::new();
for part in list.trim().split(',') {
let (a, b) = part.split_once('-').unwrap_or((part, part));
let (Ok(a), Ok(b)) = (a.trim().parse::<usize>(), b.trim().parse::<usize>()) else { return false };
siblings.extend((a..=b).filter(|s| *s != cpu));
}
if siblings.is_empty() {
return true;
}
let sample = |cpu: usize| -> Option<(u64, u64)> {
let stat = fs::read_to_string("/proc/stat").ok()?;
let line = stat.lines().find(|l| l.starts_with(&format!("cpu{cpu} ")))?;
let f: Vec<u64> = line.split_whitespace().skip(1).filter_map(|x| x.parse().ok()).collect();
let idle = f.get(3)? + f.get(4).copied().unwrap_or(0);
Some((f.iter().sum(), idle))
};
let before: Vec<_> = siblings.iter().map(|s| sample(*s)).collect();
std::thread::sleep(std::time::Duration::from_millis(200));
siblings.iter().zip(before).all(|(s, b)| match (b, sample(*s)) {
(Some(b), Some(a)) => {
let total = a.0.saturating_sub(b.0);
let idle = a.1.saturating_sub(b.1);
total > 0 && (total - idle.min(total)) * 20 < total
}
_ => false,
})
}
fn rustc_info() -> (String, String) {
let rustc = std::env::var("RUSTC").unwrap_or_else(|_| "rustc".to_owned());
let triple = if cfg!(windows) { "x86_64-pc-windows-msvc" } else { "x86_64-unknown-linux-gnu" };
let version = Command::new(rustc)
.arg("--version")
.output()
.ok()
.filter(|o| o.status.success())
.and_then(|o| String::from_utf8(o.stdout).ok())
.map_or_else(|| "unknown (rustc not runnable at record time)".to_owned(), |s| s.trim().to_owned());
(version, triple.to_owned())
}
fn host_os() -> String {
if cfg!(target_os = "linux")
&& let Ok(text) = fs::read_to_string("/etc/os-release")
&& let Some(l) = text.lines().find(|l| l.starts_with("PRETTY_NAME="))
{
return l["PRETTY_NAME=".len()..].trim_matches('"').to_owned();
}
std::env::consts::OS.to_owned()
}
fn cpu_model_of(report: &[String]) -> String {
report
.iter()
.find(|l| l.starts_with("cpu: logical "))
.and_then(|l| l.split_once("): ").map(|x| x.1))
.and_then(|rest| rest.split(';').next())
.map_or_else(|| "unknown model".to_owned(), |s| s.trim().to_owned())
}
struct Options {
out: Option<PathBuf>,
pin: usize,
machine_role: Option<String>,
trees: Vec<String>,
tree: Option<String>,
}
fn parse_options(args: &[String]) -> Result<Options, String> {
let mut o = Options { out: None, pin: 0, machine_role: None, trees: TREES.iter().map(|t| (*t).to_owned()).collect(), tree: None };
let mut it = args.iter();
while let Some(a) = it.next() {
let mut value = |what: &str| it.next().cloned().ok_or_else(|| format!("{what} needs a value"));
match a.as_str() {
"--out" => o.out = Some(PathBuf::from(value("--out")?)),
"--pin" => o.pin = value("--pin")?.parse().map_err(|_| "--pin takes a logical CPU number".to_owned())?,
"--machine-role" => o.machine_role = Some(value("--machine-role")?),
"--trees" => o.trees = value("--trees")?.split(',').map(str::to_owned).collect(),
"--tree" => o.tree = Some(value("--tree")?),
other => return Err(format!("unknown option {other}")),
}
}
if let Some(bad) = o.trees.iter().find(|t| !TREES.contains(&t.as_str())) {
return Err(format!("unknown tree {bad} (avx512 | avx2)"));
}
Ok(o)
}
fn cmd_compare(dir: &Path, opts: &Options) -> Result<ExitCode, String> {
let started = now_utc();
let verified = match verify_dir(dir) {
Ok(v) => v,
Err(e) => {
println!("{e}");
return Ok(ExitCode::from(if e.incomplete { 2 } else { 1 }));
}
};
println!("KAB1 directory verified: {} files, {} cases, manifest sha256 {}", verified.file_count, verified.cases.len(), verified.manifest_sha256);
let out = opts.out.clone().unwrap_or_else(|| {
let name = dir.file_name().map_or_else(|| "kab1".to_owned(), |n| n.to_string_lossy().into_owned());
dir.parent().unwrap_or(Path::new(".")).join(format!("{name}.rust"))
});
if out.starts_with(dir) || dir.starts_with(&out) {
return Err("--out must not contain or lie inside the KAB1 directory".to_owned());
}
if out.exists() && fs::read_dir(&out).map_err(|e| format!("{}: {e}", out.display()))?.next().is_some() {
return Err(format!("{} exists and is not empty (nothing is overwritten or deleted)", out.display()));
}
let records = out.join("records");
fs::create_dir_all(&records).map_err(|e| format!("{}: {e}", records.display()))?;
let exe = std::env::current_exe().map_err(|e| format!("current_exe: {e}"))?;
let machine_role = opts.machine_role.clone().or_else(|| std::env::var("HOSTNAME").ok()).or_else(|| std::env::var("COMPUTERNAME").ok()).unwrap_or_else(|| "unknown".to_owned());
let (rustc_version, triple) = rustc_info();
let flags = format!("cargo profile {}; RUSTFLAGS={:?}; target-cpu default", if cfg!(debug_assertions) { "dev" } else { "release" }, std::env::var("RUSTFLAGS").unwrap_or_default());
let mut all_equal = true;
let mut cells = 0usize;
for tree in &opts.trees {
let sibling = sibling_idle(opts.pin);
let mut cmd = Command::new(&exe);
cmd.arg("run-tree").arg(dir).args(["--tree", tree, "--out"]).arg(&out).args(["--pin", &opts.pin.to_string()]);
for (k, _) in std::env::vars() {
if k.starts_with("STRATA_") || k.starts_with("LELEKA_") {
cmd.env_remove(k);
}
}
cmd.env("LELEKA_CPU_POOL_PIN_HOST", "off");
if tree == "avx2" {
cmd.env("STRATA_FORCE_AVX2", "1");
}
let res = cmd.output().map_err(|e| format!("cannot start the {tree} process: {e}"))?;
let stdout = String::from_utf8_lossy(&res.stdout).into_owned();
let report: Vec<String> = stdout.lines().filter_map(|l| l.strip_prefix("REPORT ")).map(str::to_owned).collect();
match res.status.code() {
Some(0) => {}
Some(3) if tree == "avx512" && verified.provenance.avx512_ok == Some(false) => {
println!("tree avx512: SKIPPED, this host has no AVX-512 (manifest avx512_ok=false; the reference trees are identical by construction)");
continue;
}
code => {
eprint!("{}", String::from_utf8_lossy(&res.stderr));
println!("tree {tree}: the Rust process failed (exit {code:?})");
return Ok(ExitCode::from(1));
}
}
println!("tree {tree}: {}", report.iter().find(|l| l.starts_with("cpu: process kernel family")).map_or("", String::as_str));
let tree_name: &str = TREES.iter().find(|t| **t == tree.as_str()).copied().unwrap_or("avx2");
for c in &verified.cases {
let ours_name = format!("case-{}.rust-{tree}.out", c.id);
let ours = read_out(&out.join(&ours_name), &ours_name, c.rows, tree, None).map_err(|e| e.to_string())?;
let o = c.outs.iter().find(|o| o.tree == tree_name).ok_or("missing reference out")?;
let reference = read_out(&verified.dir.join(&o.name), &o.name, c.rows, tree, Some((&o.sha256, o.bytes))).map_err(|e| e.to_string())?;
let outcome = compare_bits(&ours, &reference, c.tolerance.as_ref());
let label = match (&c.tolerance, outcome.equal()) {
(None, true) => "bitwise EQUAL".to_owned(),
(None, false) => "bitwise NOT EQUAL".to_owned(),
(Some(t), eq) => format!("{} within tolerance {:e} (metric {TOLERANCE_METRIC}; basis: {})", if eq { "EQUAL" } else { "NOT EQUAL" }, t.value, t.basis),
};
let detail = match outcome.first_mismatch {
Some((i, a, b)) => format!("; {} of {} values differ, first at {i}: ours {a:#010x} reference {b:#010x}, max abs error {:e}", outcome.mismatches, outcome.compared, outcome.max_abs_error),
None => format!("; {} values", outcome.compared),
};
println!("case {} [{tree}] {label}{detail}", c.id);
all_equal &= outcome.equal();
cells += 1;
let record = record_json(&RecordInput {
record_id: format!("kab1-{}-{}-{tree}-{}", verified.provenance.run_id, c.id, started.replace([':', '-'], "")),
created_utc: now_utc(),
run_started_utc: started.clone(),
machine_role: machine_role.clone(),
cpu_model: cpu_model_of(&report),
os: host_os(),
ours_compiler: "rustc".to_owned(),
ours_version: rustc_version.clone(),
ours_triple: triple.clone(),
ours_flags: flags.clone(),
tree: tree_name,
verified: &verified,
case: c,
pin_cpu: opts.pin,
sibling_idle: sibling,
outcome: &outcome,
});
let path = records.join(format!("case-{}.{tree}.record.json", c.id));
fs::write(&path, record).map_err(|e| format!("{}: {e}", path.display()))?;
}
}
println!("compared {cells} cells; records in {}; {}", records.display(), if all_equal { "ALL EQUAL" } else { "NOT ALL EQUAL" });
Ok(if all_equal && cells > 0 { ExitCode::SUCCESS } else { ExitCode::from(1) })
}
// ------------------------------------------------------------------------------------------------ main
fn usage() -> ExitCode {
eprintln!("usage: kernel_ab verify D | compare D [--out R] [--pin CPU] [--machine-role NAME] [--trees avx512,avx2] | run-tree D --tree T --out R [--pin CPU]");
ExitCode::from(64)
}
fn main() -> ExitCode {
let args: Vec<String> = std::env::args().skip(1).collect();
let (Some(cmd), Some(dir)) = (args.first(), args.get(1)) else { return usage() };
let dir = Path::new(dir);
let opts = match parse_options(&args[2..]) {
Ok(o) => o,
Err(e) => {
eprintln!("kernel_ab: {e}");
return usage();
}
};
let result = match cmd.as_str() {
"verify" => match verify_dir(dir) {
Ok(v) => {
println!("OK {} files (manifest sha256 {})", v.file_count, v.manifest_sha256);
Ok(ExitCode::SUCCESS)
}
Err(e) => {
println!("{e}");
Ok(ExitCode::from(if e.incomplete { 2 } else { 1 }))
}
},
"compare" => cmd_compare(dir, &opts),
"run-tree" => match (&opts.tree, &opts.out) {
(Some(t), Some(o)) => cmd_run_tree(dir, t, o, opts.pin),
_ => return usage(),
},
_ => return usage(),
};
result.unwrap_or_else(|e| {
eprintln!("kernel_ab: {e}");
ExitCode::from(1)
})
}
// ------------------------------------------------------------------------------------------------ tests
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicUsize, Ordering};
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);
}
}
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>,
}
/// 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 cases = Vec::new();
let mut files = Vec::new();
for s in specs {
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 = 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()
);
files.push(format!("\"case-{id}.in\": {{\"sha256\": \"{}\", \"bytes\": {}}}", sha_hex(&inb), inb.len()));
for (k, tree) in TREES.iter().enumerate() {
let ob = out_file(s.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()));
}
cases.push(entry + "}");
}
let manifest = format!(
"{{\"format\": \"KAB1\", \"version\": 1, \"run_id\": \"synthetic\", \"writer\": \"cpp\", \"provenance\": {{\"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\"}}}}, \"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}")
}
#[test]
fn a_good_directory_verifies() {
let t = TempDir::new();
build(&t.0, &two_cases(), |_| {});
let v = verify_dir(&t.0).unwrap();
assert_eq!(v.cases.len(), 2);
assert_eq!(v.file_count, 2 * 3 + 1);
assert_eq!(v.manifest_sha256.len(), 64);
assert_eq!(v.cases[0].in_sha256, sha_hex(&fs::read(t.0.join("case-42-42-r2.in")).unwrap()));
}
#[test]
fn a_flipped_byte_refuses_the_directory_and_names_the_file() {
let t = TempDir::new();
build(&t.0, &one_case(), |_| {});
let p = t.0.join(id("in"));
let mut b = fs::read(&p).unwrap();
b[IN_HEADER + 7] ^= 0x40;
fs::write(&p, b).unwrap();
let e = verify_dir(&t.0).unwrap_err();
assert_eq!(e.file, "case-42-42-r1.in");
assert!(e.reason.contains("sha256"), "{e}");
}
#[test]
fn a_truncated_file_refuses_the_directory_and_names_the_file() {
let t = TempDir::new();
build(&t.0, &one_case(), |_| {});
let p = t.0.join(id("cpp-avx2.out"));
let b = fs::read(&p).unwrap();
fs::write(&p, &b[..b.len() - 4]).unwrap();
let e = verify_dir(&t.0).unwrap_err();
assert_eq!(e.file, "case-42-42-r1.cpp-avx2.out");
assert!(e.reason.contains("length"), "{e}");
}
#[test]
fn a_wrong_magic_is_refused() {
let t = TempDir::new();
build(&t.0, &one_case(), |b| b[0] ^= 0xff);
let e = verify_dir(&t.0).unwrap_err();
assert_eq!(e.file, "case-42-42-r1.in");
assert!(e.reason.contains("magic"), "{e}");
}
#[test]
fn a_wrong_version_is_refused() {
let t = TempDir::new();
build(&t.0, &one_case(), |b| b[4] = 2);
let e = verify_dir(&t.0).unwrap_err();
assert_eq!(e.file, "case-42-42-r1.in");
assert!(e.reason.contains("version"), "{e}");
}
#[test]
fn a_byte_count_that_disagrees_with_the_format_is_refused() {
let t = TempDir::new();
build(&t.0, &one_case(), |b| {
let wrong = (le32(b, 28) + 18).to_le_bytes();
b[28..32].copy_from_slice(&wrong);
});
let e = verify_dir(&t.0).unwrap_err();
assert_eq!(e.file, "case-42-42-r1.in");
assert!(e.reason.contains("format-derived"), "{e}");
}
#[test]
fn a_non_finite_fp16_header_is_refused() {
let t = TempDir::new();
// the manifest records the hash of the mutated file, so only the FP16 rule can refuse it
build(&t.0, &one_case(), |b| {
let at = IN_HEADER + 18 * 3;
b[at] = 0x00;
b[at + 1] = 0x7c; // FP16 +inf
});
let e = verify_dir(&t.0).unwrap_err();
assert_eq!(e.file, "case-42-42-r1.in");
assert!(e.reason.contains("non-finite FP16"), "{e}");
}
#[test]
fn a_non_finite_activation_is_refused() {
let t = TempDir::new();
build(&t.0, &one_case(), |b| {
let at = b.len() - 4;
b[at..].copy_from_slice(&f32::NAN.to_bits().to_le_bytes());
});
let e = verify_dir(&t.0).unwrap_err();
assert!(e.reason.contains("non-finite activation"), "{e}");
}
#[test]
fn a_missing_manifest_is_incomplete_and_named() {
let t = TempDir::new();
build(&t.0, &one_case(), |_| {});
fs::remove_file(t.0.join("manifest.json")).unwrap();
let e = verify_dir(&t.0).unwrap_err();
assert_eq!(e.file, "manifest.json");
assert!(e.incomplete);
assert!(e.to_string().contains("manifest.json"));
}
#[test]
fn an_extra_or_missing_file_refuses_the_directory() {
let t = TempDir::new();
build(&t.0, &one_case(), |_| {});
fs::write(t.0.join("stray.txt"), b"x").unwrap();
assert_eq!(verify_dir(&t.0).unwrap_err().file, "stray.txt");
fs::remove_file(t.0.join("stray.txt")).unwrap();
fs::remove_file(t.0.join(id("cpp-avx512.out"))).unwrap();
assert_eq!(verify_dir(&t.0).unwrap_err().file, "case-42-42-r1.cpp-avx512.out");
}
#[test]
fn an_absurd_length_is_refused_without_taking_a_buffer() {
// header says gate_bytes = 4 GiB - 16; the pure header check refuses it before any buffer exists
let mut h = [0u8; IN_HEADER];
h.copy_from_slice(&in_file(42, 42, 1)[..IN_HEADER]);
h[28..32].copy_from_slice(&(u32::MAX - 15).to_le_bytes());
BUFFERS.with(|c| c.set(0));
assert!(validate_in_header(&h, 1 << 20).unwrap_err().contains("format-derived"));
assert_eq!(BUFFERS.with(Cell::get), 0);
// and through the file reader: manifest and file agree on a file whose header lies about its size
let t = TempDir::new();
build(&t.0, &one_case(), |b| b[28..32].copy_from_slice(&(u32::MAX - 15).to_le_bytes()));
BUFFERS.with(|c| c.set(0));
let (m, _) = (fs::read(t.0.join("manifest.json")).unwrap(), 0);
let (_, cases, _) = parse_manifest(&parse_json(&m).unwrap()).unwrap();
let e = read_case_in(&t.0, &cases[0]).err().unwrap();
assert!(e.reason.contains("format-derived"), "{e}");
assert_eq!(BUFFERS.with(Cell::get), 0, "a buffer was taken before the header was validated");
// a manifest that declares an absurd length for a file is refused before a buffer too
let mut lying = cases[0].clone();
lying.in_bytes = u64::MAX;
assert!(read_case_in(&t.0, &lying).unwrap_err().reason.contains("differs from the manifest"));
assert_eq!(BUFFERS.with(Cell::get), 0);
// the good path takes exactly one buffer per file
let g = TempDir::new();
build(&g.0, &one_case(), |_| {});
BUFFERS.with(|c| c.set(0));
let (_, cases, _) = parse_manifest(&parse_json(&fs::read(g.0.join("manifest.json")).unwrap()).unwrap()).unwrap();
read_case_in(&g.0, &cases[0]).unwrap();
assert_eq!(BUFFERS.with(Cell::get), 1);
}
#[test]
fn a_tolerance_needs_basis_metric_and_a_time_before_the_reference_run() {
let ok = "{\"value\": 0.003, \"metric\": \"max_abs_error_over_max_abs_reference\", \"basis\": \"order-only difference\", \"basis_written_utc\": \"2026-10-28T10:00:00Z\"}";
let t = TempDir::new();
build(&t.0, &[Spec { gu: 42, down: 42, rows: 1, tolerance: Some(ok) }], |_| {});
let v = verify_dir(&t.0).unwrap();
assert_eq!(v.cases[0].tolerance.as_ref().unwrap().value, 0.003);
for (bad, why) in [
(ok.replace("0.003", "0"), "positive"),
(ok.replace("max_abs_error_over_max_abs_reference", "ulp"), "metric"),
(ok.replace("order-only difference", " "), "basis"),
(ok.replace("2026-10-28T10:00:00Z", "2026-10-28T20:00:00Z"), "after the reference run"),
] {
let leaked: &'static str = Box::leak(bad.into_boxed_str());
let d = TempDir::new();
build(&d.0, &[Spec { gu: 42, down: 42, rows: 1, tolerance: Some(leaked) }], |_| {});
let e = verify_dir(&d.0).unwrap_err();
assert_eq!(e.file, "manifest.json");
assert!(e.reason.contains(why), "{why}: {e}");
}
}
#[test]
fn the_json_reader_handles_the_manifest_forms_and_refuses_the_rest() {
let j = parse_json(b"{\"a\": [1, -2.5e3, true, null, \"x\\n\\u00e9\\ud83d\\ude00\"], \"b\": {}}").unwrap();
assert_eq!(j.get("a"), Some(&Json::Arr(vec![Json::Num("1".into()), Json::Num("-2.5e3".into()), Json::Bool(true), Json::Null, Json::Str("x\n\u{e9}\u{1f600}".into())])));
assert_eq!(parse_json(b"{\"s\": 18446744073709551615}").unwrap().uint("s").unwrap(), u64::MAX);
for bad in ["{\"a\": 1, \"a\": 2}", "{\"a\": 1,}", "[1 2]", "{\"a\": \"\\ud800\"}", "{} x", "", "{\"a\": 01x}", "\"\u{1}\""] {
assert!(parse_json(bad.as_bytes()).is_err(), "{bad}");
}
assert!(parse_json("[".repeat(40).as_bytes()).is_err());
}
#[test]
fn bitwise_compare_sees_signed_zero_and_one_ulp_and_tolerance_is_normalised() {
let a = [1.0f32.to_bits(), 0.0f32.to_bits(), 2.0f32.to_bits()];
assert!(compare_bits(&a, &a, None).equal());
let neg0 = [1.0f32.to_bits(), (-0.0f32).to_bits(), 2.0f32.to_bits()];
let o = compare_bits(&neg0, &a, None);
assert_eq!((o.mismatches, o.first_mismatch), (1, Some((1, (-0.0f32).to_bits(), 0.0f32.to_bits()))));
let ulp = [1.0f32.to_bits(), 0.0f32.to_bits(), 2.0f32.to_bits() + 1];
assert_eq!(compare_bits(&ulp, &a, None).mismatches, 1);
let tol = Tolerance { value: 1e-6, basis: "test".into(), basis_written_utc: "2026-01-01T00:00:00Z".into() };
assert!(compare_bits(&ulp, &a, Some(&tol)).equal());
let far = [1.0f32.to_bits(), 0.0f32.to_bits(), 2.1f32.to_bits()];
assert_eq!(compare_bits(&far, &a, Some(&tol)).mismatches, 1);
assert_eq!(compare_bits(&a[..2], &a, None).mismatches, 1);
}
#[test]
fn our_trees_run_on_a_verified_synthetic_case_and_the_record_is_well_formed() {
let t = TempDir::new();
build(&t.0, &one_case(), |_| {});
let v = verify_dir(&t.0).unwrap();
let case = read_case_in(&v.dir, &v.cases[0]).unwrap();
let mut pool = DirectCpuPool::new(1).unwrap();
let first = compute_case(&mut pool, &case).unwrap();
let second = compute_case(&mut pool, &case).unwrap();
assert_eq!(first.len(), H);
assert!(first.iter().zip(&second).all(|(a, b)| a.to_bits() == b.to_bits()), "the same case twice must be bit-identical");
let path = t.0.join("ours.rust-avx2.out");
write_out(&path, 1, "avx2", &first).unwrap();
let back = read_out(&path, "ours.rust-avx2.out", 1, "avx2", None).unwrap();
assert_eq!(back, first.iter().map(|v| v.to_bits()).collect::<Vec<_>>());
let outcome = compare_bits(&back, &back, None);
let json = record_json(&RecordInput {
record_id: "kab1-synthetic-r".into(),
created_utc: "2026-10-28T20:00:00Z".into(),
run_started_utc: "2026-10-28T19:59:00Z".into(),
machine_role: "m\"1".into(),
cpu_model: "cpu".into(),
os: "os".into(),
ours_compiler: "rustc".into(),
ours_version: "rustc 1.99.0".into(),
ours_triple: "x86_64-unknown-linux-gnu".into(),
ours_flags: "f".into(),
tree: "avx2",
verified: &v,
case: &v.cases[0],
pin_cpu: 0,
sibling_idle: true,
outcome: &outcome,
});
let rec = parse_json(json.as_bytes()).unwrap();
for key in ["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"] {
assert!(rec.get(key).is_some(), "{key}");
}
assert_eq!(rec.req("equality").unwrap().str("verdict").unwrap(), "EQUAL");
assert_eq!(rec.req("machine").unwrap().str("machine_role").unwrap(), "m\"1");
assert_eq!(rec.str("kab1_manifest_sha256").unwrap(), v.manifest_sha256);
}
#[test]
fn utc_formatting_is_exact() {
assert_eq!(utc_of(0), "1970-01-01T00:00:00Z");
assert_eq!(utc_of(1_782_000_000), "2026-06-21T00:00:00Z");
assert!(is_utc(&now_utc()));
}
}