Confirmed against the C++ in engine/strata and fixed: - rust_native_general.rs group_dot_bytes_policy omitted the `gu == 23 && !avx512` multi-token branch of native_expert.cpp native_gu_rows (`nt >= mt_min && (iq512_supported || (!cpu512 && iq256_supported))`); rust_pool.rs had it since STRA-324. The choice is now one function, gu_multi_route, shared in shape with the pool. Regression: a differential test (re-runs itself with STRATA_FORCE_AVX2=1 on an AVX-512 CPU) fails with a 1-ULP difference on the old code, plus a routing-table test. - rust_legacy.rs row256 (STRATA_CPU_YMM=1 on an AVX-512 CPU) now fuses `corr += d*(hx0+hx1)` like expert.cpp row_dot (line 242) and row_dot_multi (line 294) under GCC -mfma. Regression: scalar model, fails on old code. NOT changed, unconfirmed (need the pinned ggml source, which is not in the repo): rust_kq.rs small_dot `sums += m*s`, rust_k_blocks.rs mins_sum, rust_ggml_extra.rs iq1 scalar. KAB1: new `--cases ext` (72 cases; the 40 of `all` are untouched) adds token counts 4-7 for the row-type list and IQ2_XXS / IQ2_XS at 1..8 tokens; GateUpFormat gains Iq2Xxs / Iq2Xs (additive; the runtime still admits only 18/21/22/23/42). The C++ driver edits are list-only and were NOT compiled here (no ggml). 16 tokens exceed MAXT and the KAB1 header and are not covered. New Rust-only test token_count_invariance: the first two tokens of a group are bit-identical for groups of 2..8 tokens on all 14 gate/up x down pairs. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
3348 lines
162 KiB
Rust
3348 lines
162 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] [--case ID]
|
|
//! internal: one fresh process, one tree (T = avx512 | avx2), all cases or only ID
|
|
//!
|
|
//! Timing is not in `verify` / `compare`. The records written by `compare` carry the fields the schema requires for timing with the
|
|
//! explicit NOT_MEASURED marker (see `NOT_MEASURED`), never a measurement. Timing is the second half (STRA-318, S0.8b2):
|
|
//!
|
|
//! kernel_ab time --run-dir D --case ID --slices N --pin CPU --out F.json [--slice-ms 60] [--regime both|resident|streamed]
|
|
//! [--llc-bytes B]
|
|
//! the Rust twin of `kab time` (tools/kernel-ab, STRA-317): ONE fresh process times ONE
|
|
//! case in the resident and the streamed regime on the pinned CPU and writes the KAB1-time
|
|
//! JSON (writer "rust"); no statistics
|
|
//! kernel_ab alternate --run-dir D --case ID --rounds N --batch K --pin CPU --schedule FILE [--seed S] [--out R] [--slices N]
|
|
//! [--slice-ms MS] [--llc-bytes B] [--machine-role NAME] [--kab PATH]
|
|
//! the alternation runner (ARCHITECT 395f0394 sec 1.3): std::process::Command only. Per
|
|
//! round it starts FRESH processes for the cells {cpp, rust} x {avx512, avx2} (each twice,
|
|
//! a and b, for the A/A pairs) in the order of a seeded schedule file written before the
|
|
//! first run, and writes COMPONENT_KERNEL round records. It computes NO statistics: no
|
|
//! class, no interval, no A/A verdict (those are S0.10b, STRA-313).
|
|
//!
|
|
//! 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::{BTreeMap, BTreeSet};
|
|
use std::ffi::OsString;
|
|
use std::fs::{self, File};
|
|
use std::io::{Read, Write};
|
|
use std::path::{Path, PathBuf};
|
|
use std::process::{Command, ExitCode};
|
|
use std::sync::OnceLock;
|
|
use std::time::{Instant, 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); 7] = [
|
|
(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"),
|
|
(16, GateUpFormat::Iq2Xxs, 256, 66, "IQ2_XXS"),
|
|
(17, GateUpFormat::Iq2Xs, 256, 74, "IQ2_XS"),
|
|
];
|
|
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")),
|
|
}
|
|
}
|
|
fn float(&self, key: &str) -> Result<f64, String> {
|
|
match self.req(key)? {
|
|
Json::Num(n) => n.parse::<f64>().ok().filter(|v| v.is_finite()).ok_or_else(|| format!("key {key:?} is not a finite number")),
|
|
_ => Err(format!("key {key:?} is not a number")),
|
|
}
|
|
}
|
|
/// A number, or None for a JSON null (the C++ writer prints null for a value it could not measure).
|
|
fn float_or_null(&self, key: &str) -> Result<Option<f64>, String> {
|
|
match self.req(key)? {
|
|
Json::Null => Ok(None),
|
|
_ => self.float(key).map(Some),
|
|
}
|
|
}
|
|
fn flag(&self, key: &str) -> Result<bool, String> {
|
|
match self.req(key)? {
|
|
Json::Bool(b) => Ok(*b),
|
|
_ => Err(format!("key {key:?} is not a boolean")),
|
|
}
|
|
}
|
|
fn array(&self, key: &str) -> Result<&[Json], String> {
|
|
match self.req(key)? {
|
|
Json::Arr(a) => Ok(a),
|
|
_ => Err(format!("key {key:?} is not an array")),
|
|
}
|
|
}
|
|
}
|
|
|
|
// ------------------------------------------------------------------------------------------------ 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)
|
|
}
|
|
|
|
/// Reads and parses `manifest.json` (size cap first). Returns its bytes (the caller hashes them), the provenance, the cases and the flat
|
|
/// files table. A missing manifest is the `incomplete` refusal.
|
|
fn read_manifest(dir: &Path) -> Result<(Vec<u8>, Provenance, Vec<CaseEntry>, FileTable), 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)?;
|
|
Ok((mbytes, provenance, cases, files))
|
|
}
|
|
|
|
/// 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 mname = "manifest.json";
|
|
let r = |reason: String| Refusal::new(mname, reason);
|
|
let (mbytes, provenance, cases, files) = read_manifest(dir)?;
|
|
// 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, only_case: Option<&str>) -> 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:?}"))?;
|
|
let mut done = 0usize;
|
|
for c in verified.cases.iter().filter(|c| only_case.is_none_or(|id| c.id == id)) {
|
|
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)?;
|
|
done += 1;
|
|
}
|
|
if done == 0 {
|
|
return Err(format!("case {} is not in the manifest", only_case.unwrap_or("?")));
|
|
}
|
|
println!("RUN-TREE {tree} cases={done}");
|
|
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) {
|
|
// $RUSTC, then `rustc` on the PATH, then the rustup shim of the user (a non-login shell has no cargo bin directory on its PATH)
|
|
let home = std::env::var("HOME").or_else(|_| std::env::var("USERPROFILE")).unwrap_or_default();
|
|
let shim = format!("{home}/.cargo/bin/{}", if cfg!(windows) { "rustc.exe" } else { "rustc" });
|
|
let candidates = [std::env::var("RUSTC").unwrap_or_else(|_| "rustc".to_owned()), "rustc".to_owned(), shim];
|
|
let triple = if cfg!(windows) { "x86_64-pc-windows-msvc" } else { "x86_64-unknown-linux-gnu" };
|
|
let version = candidates
|
|
.iter()
|
|
.find_map(|rustc| 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>,
|
|
case: 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, case: 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")?),
|
|
"--case" => o.case = Some(value("--case")?),
|
|
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 parent_env: Vec<(OsString, OsString)> = std::env::vars_os().collect();
|
|
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 probe = Proc { imp: Impl::Rust, tree: TREES.iter().find(|t| **t == tree.as_str()).copied().unwrap_or("avx2"), rep: 'a' };
|
|
let mut cmd = scrubbed_command(&exe, &parent_env, &cell_env(&probe));
|
|
cmd.arg("run-tree").arg(dir).args(["--tree", tree, "--out"]).arg(&out).args(["--pin", &opts.pin.to_string()]);
|
|
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) })
|
|
}
|
|
|
|
// ------------------------------------------------------------------------------------------------ flags (time, alternate)
|
|
|
|
struct Flags(Vec<(String, String)>);
|
|
|
|
impl Flags {
|
|
fn parse(args: &[String], known: &[&str]) -> Result<Self, String> {
|
|
let mut items: Vec<(String, String)> = Vec::new();
|
|
let mut it = args.iter();
|
|
while let Some(a) = it.next() {
|
|
let name = a.strip_prefix("--").ok_or_else(|| format!("unexpected argument {a}"))?;
|
|
if !known.contains(&name) {
|
|
return Err(format!("unknown option {a}"));
|
|
}
|
|
if items.iter().any(|(k, _)| k == name) {
|
|
return Err(format!("option {a} given twice"));
|
|
}
|
|
let v = it.next().ok_or_else(|| format!("{a} needs a value"))?;
|
|
items.push((name.to_owned(), v.clone()));
|
|
}
|
|
Ok(Self(items))
|
|
}
|
|
fn get(&self, k: &str) -> Option<&str> {
|
|
self.0.iter().find(|(n, _)| n == k).map(|(_, v)| v.as_str())
|
|
}
|
|
fn req(&self, k: &str) -> Result<&str, String> {
|
|
self.get(k).ok_or_else(|| format!("--{k} is required"))
|
|
}
|
|
fn number<T: std::str::FromStr>(&self, k: &str) -> Result<Option<T>, String> {
|
|
self.get(k).map(|v| v.parse::<T>().map_err(|_| format!("--{k} {v:?} is not a valid number"))).transpose()
|
|
}
|
|
}
|
|
|
|
// ------------------------------------------------------------------------------------------------ clocks and host facts
|
|
|
|
/// The 60 ms slice of `tq_cpu_parity.cpp:461` (`slice_ms = quick ? 40 : 60`), the same value `kab time` uses.
|
|
const DEFAULT_SLICE_MS: f64 = 60.0;
|
|
/// `tq_cpu_parity.cpp:303`: a slice whose calibrated clock moved by more than this fraction is dropped. Copied, not chosen here.
|
|
const CLOCK_MOVED_FRACTION: f64 = 0.05;
|
|
/// An SMT sibling busier than this fraction is not idle (the 5 percent rule of `sibling_idle`).
|
|
const SIBLING_BUSY_LIMIT: f64 = 0.05;
|
|
const ALIGN: usize = 4096;
|
|
/// Cycles of one step of the calibration chain `x = (x * k) ^ (x >> 17)`: a 64-bit multiply (3 cycles on Intel Skylake to Golden Cove
|
|
/// and AMD Zen 1 to 5) then an xor (1 cycle); the shift runs beside the multiply.
|
|
const CHAIN_STEP_CYCLES: f64 = 4.0;
|
|
const CLOCK_METHOD: &str = "chain of dependent steps x = (x * k) ^ (x >> 17), 4 cycles per step (3 multiply + 1 xor), 1000000 iterations of 4 steps, ghz = 4 * 4e6 / (elapsed ns); before and after every slice";
|
|
|
|
fn mono_ns() -> u64 {
|
|
static ORIGIN: OnceLock<Instant> = OnceLock::new();
|
|
ORIGIN.get_or_init(Instant::now).elapsed().as_nanos() as u64
|
|
}
|
|
|
|
/// The core clock in GHz from a chain of dependent steps (safe code: the C++ chain of dependent adds needs inline assembly). A plain
|
|
/// chain of multiplies by an opaque constant is folded by LLVM (measured: 175 GHz), so every step also xors in a shifted copy of the
|
|
/// running value, which no reassociation can remove.
|
|
fn core_ghz() -> f64 {
|
|
let k = std::hint::black_box(0x9E37_79B9_7F4A_7C15u64 | 1);
|
|
let mut x = std::hint::black_box(1u64);
|
|
let n = 1_000_000u64;
|
|
let t0 = mono_ns();
|
|
for _ in 0..n {
|
|
x = x.wrapping_mul(k) ^ (x >> 17);
|
|
x = x.wrapping_mul(k) ^ (x >> 17);
|
|
x = x.wrapping_mul(k) ^ (x >> 17);
|
|
x = x.wrapping_mul(k) ^ (x >> 17);
|
|
}
|
|
let dt = mono_ns().saturating_sub(t0).max(1);
|
|
std::hint::black_box(x);
|
|
CHAIN_STEP_CYCLES * 4.0 * n as f64 / dt as f64
|
|
}
|
|
|
|
fn median_of(v: &[f64]) -> f64 {
|
|
if v.is_empty() {
|
|
return 0.0;
|
|
}
|
|
let mut s = v.to_vec();
|
|
s.sort_by(f64::total_cmp);
|
|
s[s.len() / 2]
|
|
}
|
|
|
|
/// Nearest-rank percentile of raw slice values (a description of the slices, not an inference).
|
|
fn percentile_of(v: &[f64], p: f64) -> f64 {
|
|
if v.is_empty() {
|
|
return 0.0;
|
|
}
|
|
let mut s = v.to_vec();
|
|
s.sort_by(f64::total_cmp);
|
|
s[((s.len() - 1) as f64 * p).round() as usize]
|
|
}
|
|
|
|
fn jnum(v: f64, decimals: usize) -> String {
|
|
if v.is_finite() { format!("{v:.decimals$}") } else { "null".to_owned() }
|
|
}
|
|
|
|
fn read_text(path: &str) -> String {
|
|
fs::read_to_string(path).map(|s| s.trim().to_owned()).unwrap_or_default()
|
|
}
|
|
|
|
fn parse_cpu_list(s: &str) -> Vec<usize> {
|
|
let mut v = Vec::new();
|
|
for part in s.trim().split(',').filter(|p| !p.is_empty()) {
|
|
let (a, b) = part.split_once('-').unwrap_or((part, part));
|
|
if let (Ok(a), Ok(b)) = (a.trim().parse::<usize>(), b.trim().parse::<usize>()) {
|
|
v.extend(a..=b);
|
|
}
|
|
}
|
|
v
|
|
}
|
|
|
|
fn parse_size(s: &str) -> u64 {
|
|
let digits: String = s.chars().take_while(char::is_ascii_digit).collect();
|
|
let n = digits.parse::<u64>().unwrap_or(0);
|
|
match s[digits.len()..].chars().next() {
|
|
Some('K' | 'k') => n << 10,
|
|
Some('M' | 'm') => n << 20,
|
|
Some('G' | 'g') => n << 30,
|
|
_ => n,
|
|
}
|
|
}
|
|
|
|
struct Llc {
|
|
level: u32,
|
|
bytes: u64,
|
|
source: String,
|
|
}
|
|
|
|
/// Linux: the highest-level data or unified cache of `cpu` from sysfs. Elsewhere: None (the caller passes `--llc-bytes`).
|
|
fn llc_of_cpu(cpu: usize) -> Option<Llc> {
|
|
let mut best: Option<Llc> = None;
|
|
for i in 0..16 {
|
|
let d = format!("/sys/devices/system/cpu/cpu{cpu}/cache/index{i}");
|
|
let (level, kind, size) = (read_text(&format!("{d}/level")), read_text(&format!("{d}/type")), read_text(&format!("{d}/size")));
|
|
if level.is_empty() || size.is_empty() || kind == "Instruction" {
|
|
continue;
|
|
}
|
|
let level_n = level.parse::<u32>().unwrap_or(0);
|
|
if best.as_ref().is_none_or(|b| level_n >= b.level) {
|
|
best = Some(Llc { level: level_n, bytes: parse_size(&size), source: format!("{d}/size = {size}") });
|
|
}
|
|
}
|
|
best.filter(|l| l.bytes > 0)
|
|
}
|
|
|
|
/// (busy, total) jiffies of one logical CPU from /proc/stat (Linux).
|
|
fn proc_stat_cpu(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 total: u64 = f.iter().take(8).sum();
|
|
Some((total - f.get(3)? - f.get(4).copied().unwrap_or(0), total))
|
|
}
|
|
|
|
fn busy_fraction(before: Option<(u64, u64)>, after: Option<(u64, u64)>) -> Option<f64> {
|
|
let (b, a) = (before?, after?);
|
|
(a.1 > b.1).then(|| (a.0.saturating_sub(b.0)) as f64 / (a.1 - b.1) as f64)
|
|
}
|
|
|
|
/// Linux: the logical CPU the calling thread last ran on (field 39 of /proc/thread-self/stat). Elsewhere: None.
|
|
fn current_cpu() -> Option<usize> {
|
|
if !cfg!(target_os = "linux") {
|
|
return None;
|
|
}
|
|
let s = fs::read_to_string("/proc/thread-self/stat").ok()?;
|
|
let rest = &s[s.rfind(')')? + 1..];
|
|
rest.split_whitespace().nth(36)?.parse().ok()
|
|
}
|
|
|
|
/// Linux: every thread of this process with the CPU it last ran on (the pool's worker is one of them).
|
|
fn observed_threads() -> Vec<(String, Option<usize>)> {
|
|
let mut v = Vec::new();
|
|
if let Ok(dir) = fs::read_dir("/proc/self/task") {
|
|
for e in dir.flatten() {
|
|
let p = e.path();
|
|
let name = read_text(&format!("{}/comm", p.display()));
|
|
let cpu = fs::read_to_string(p.join("stat")).ok().and_then(|s| s.get(s.rfind(')')? + 1..)?.split_whitespace().nth(36)?.parse().ok());
|
|
v.push((name, cpu));
|
|
}
|
|
}
|
|
v.sort();
|
|
v
|
|
}
|
|
|
|
fn is_managed_name(name: &str) -> bool {
|
|
let up = name.to_ascii_uppercase();
|
|
up.starts_with("STRATA_") || up.starts_with("LELEKA_")
|
|
}
|
|
|
|
/// Every STRATA_* / LELEKA_* variable the process sees.
|
|
fn managed_env_now() -> BTreeMap<String, String> {
|
|
std::env::vars_os().filter_map(|(k, v)| Some((k.into_string().ok()?, v.into_string().ok()?))).filter(|(k, _)| is_managed_name(k)).collect()
|
|
}
|
|
|
|
fn json_env(env: &BTreeMap<String, String>) -> String {
|
|
format!("{{{}}}", env.iter().map(|(k, v)| format!("{}: {}", jstr(k), jstr(v))).collect::<Vec<_>>().join(", "))
|
|
}
|
|
|
|
// ------------------------------------------------------------------------------------------------ time (one fresh process)
|
|
|
|
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
|
enum RegimeSel {
|
|
Both,
|
|
Resident,
|
|
Streamed,
|
|
}
|
|
|
|
#[derive(Debug)]
|
|
struct TimeArgs {
|
|
dir: PathBuf,
|
|
case: String,
|
|
slices: usize,
|
|
pin: usize,
|
|
out: PathBuf,
|
|
slice_ms: f64,
|
|
regime: RegimeSel,
|
|
llc_bytes: Option<u64>,
|
|
}
|
|
|
|
const TIME_FLAGS: [&str; 8] = ["run-dir", "case", "slices", "pin", "out", "slice-ms", "regime", "llc-bytes"];
|
|
|
|
/// The command line of `kab time` (STRA-317), checked the same way.
|
|
fn parse_time_args(args: &[String]) -> Result<TimeArgs, String> {
|
|
let f = Flags::parse(args, &TIME_FLAGS)?;
|
|
let slices = f.number::<usize>("slices")?.ok_or("--slices is required")?;
|
|
let pin = f.number::<usize>("pin")?.ok_or("--pin is required")?;
|
|
let slice_ms = f.number::<f64>("slice-ms")?.unwrap_or(DEFAULT_SLICE_MS);
|
|
if !(1..=100_000).contains(&slices) {
|
|
return Err("--slices must be 1..100000".to_owned());
|
|
}
|
|
if !(1.0..=10_000.0).contains(&slice_ms) {
|
|
return Err("--slice-ms must be 1..10000".to_owned());
|
|
}
|
|
let regime = match f.get("regime").unwrap_or("both") {
|
|
"both" => RegimeSel::Both,
|
|
"resident" => RegimeSel::Resident,
|
|
"streamed" => RegimeSel::Streamed,
|
|
_ => return Err("--regime must be both, resident or streamed".to_owned()),
|
|
};
|
|
let case = f.req("case")?.to_owned();
|
|
if !valid_id(&case) {
|
|
return Err(format!("--case {case:?} is not a plain identifier"));
|
|
}
|
|
Ok(TimeArgs {
|
|
dir: PathBuf::from(f.req("run-dir")?),
|
|
case,
|
|
slices,
|
|
pin,
|
|
out: PathBuf::from(f.req("out")?),
|
|
slice_ms,
|
|
regime,
|
|
llc_bytes: f.number::<u64>("llc-bytes")?,
|
|
})
|
|
}
|
|
|
|
/// A buffer whose usable part starts on a 4096-byte boundary.
|
|
struct Arena<T> {
|
|
buf: Vec<T>,
|
|
off: usize,
|
|
}
|
|
impl<T: Copy + Default> Arena<T> {
|
|
fn new(len: usize) -> Self {
|
|
let size = std::mem::size_of::<T>();
|
|
let buf = vec![T::default(); len + ALIGN / size];
|
|
let misalign = buf.as_ptr() as usize % ALIGN;
|
|
let off = if misalign == 0 { 0 } else { (ALIGN - misalign) / size };
|
|
Self { buf, off }
|
|
}
|
|
fn slice(&self, len: usize) -> &[T] {
|
|
&self.buf[self.off..self.off + len]
|
|
}
|
|
fn slice_mut(&mut self, len: usize) -> &mut [T] {
|
|
&mut self.buf[self.off..self.off + len]
|
|
}
|
|
}
|
|
|
|
/// The timed call: one group of one expert through the crate's public pool, exactly as `compute_case` does it.
|
|
struct Timed<'a> {
|
|
pool: DirectCpuPool,
|
|
gu: GateUpFormat,
|
|
down: DownFormat,
|
|
header: InHeader,
|
|
pairs: Vec<(usize, usize)>,
|
|
tokens: &'a [f32],
|
|
out: Vec<f32>,
|
|
}
|
|
|
|
impl Timed<'_> {
|
|
fn call(&mut self, weights: &[u8]) -> Result<(), String> {
|
|
let (g, u) = (self.header.gate, self.header.up);
|
|
let expert = BorrowedExpert { gate: &weights[..g], up: &weights[g..g + u], down: &weights[g + u..g + u + self.header.down_bytes], pairs: &self.pairs };
|
|
let experts = [expert];
|
|
let group = BorrowedGroup { tokens: self.tokens, experts: &experts, stride: 1 };
|
|
self.pool.compute_group(self.gu, self.down, &group, &mut self.out).map_err(|e| format!("compute_group failed: {e:?}"))
|
|
}
|
|
}
|
|
|
|
struct Slice {
|
|
calls: u64,
|
|
wall_ns: u64,
|
|
ns_per_call: f64,
|
|
ghz_before: f64,
|
|
ghz_after: f64,
|
|
cycles_per_call: f64,
|
|
moved: bool,
|
|
}
|
|
|
|
/// One slice of `ms` milliseconds cycling over the copies; the shape of `time_slice()` in tq_cpu_parity.cpp (lines 290-304).
|
|
fn time_slice(t: &mut Timed, copies: &[&[u8]], ms: f64, next: &mut usize) -> Result<Slice, String> {
|
|
let ghz_before = core_ghz();
|
|
let mut calls = 0u64;
|
|
let ns0 = mono_ns();
|
|
let mut ns1;
|
|
loop {
|
|
t.call(copies[*next % copies.len()])?;
|
|
*next += 1;
|
|
calls += 1;
|
|
ns1 = mono_ns();
|
|
if (ns1 - ns0) as f64 >= ms * 1e6 && calls >= 2 {
|
|
break;
|
|
}
|
|
}
|
|
let ghz_after = core_ghz();
|
|
let wall = ns1 - ns0;
|
|
let ns_per_call = wall as f64 / calls as f64;
|
|
let ghz_mean = 0.5 * (ghz_before + ghz_after);
|
|
Ok(Slice {
|
|
calls,
|
|
wall_ns: wall,
|
|
ns_per_call,
|
|
ghz_before,
|
|
ghz_after,
|
|
cycles_per_call: ns_per_call * ghz_mean,
|
|
moved: ghz_mean > 0.0 && (ghz_after - ghz_before).abs() > CLOCK_MOVED_FRACTION * ghz_before,
|
|
})
|
|
}
|
|
|
|
fn slice_json(s: &Slice, idx: usize) -> String {
|
|
format!(
|
|
"{{\"i\": {idx}, \"calls\": {}, \"wall_ns\": {}, \"ns_per_call\": {}, \"ghz_before\": {}, \"ghz_after\": {}, \"cycles_per_call\": {}}}",
|
|
s.calls,
|
|
s.wall_ns,
|
|
jnum(s.ns_per_call, 3),
|
|
jnum(s.ghz_before, 6),
|
|
jnum(s.ghz_after, 6),
|
|
jnum(s.cycles_per_call, 1)
|
|
)
|
|
}
|
|
|
|
/// Slices with their index within the regime.
|
|
type Numbered = Vec<(usize, Slice)>;
|
|
|
|
struct RegimeRun {
|
|
json: String,
|
|
kept: usize,
|
|
ok: bool,
|
|
}
|
|
|
|
struct RegimeSpec<'a> {
|
|
label: &'a str,
|
|
copies: Vec<&'a [u8]>,
|
|
expert_bytes: usize,
|
|
stride: usize,
|
|
llc: &'a Llc,
|
|
slices: usize,
|
|
slice_ms: f64,
|
|
pin: usize,
|
|
selfcheck: bool,
|
|
}
|
|
|
|
fn run_regime(t: &mut Timed, spec: &RegimeSpec) -> Result<RegimeRun, String> {
|
|
let mut next = 0usize;
|
|
// warm-up (not recorded): tables and buffers, and for STREAMED one full pass over the copies so every page is resident
|
|
for _ in 0..3 {
|
|
t.call(spec.copies[next % spec.copies.len()])?;
|
|
next += 1;
|
|
}
|
|
if spec.copies.len() > 1 {
|
|
for _ in 0..spec.copies.len() {
|
|
t.call(spec.copies[next % spec.copies.len()])?;
|
|
next += 1;
|
|
}
|
|
}
|
|
let (mut kept, mut dropped): (Numbered, Numbered) = (Vec::new(), Vec::new());
|
|
let mut migrated: Option<usize> = cfg!(target_os = "linux").then_some(0);
|
|
for i in 0..spec.slices {
|
|
let before = current_cpu();
|
|
let s = time_slice(t, &spec.copies, spec.slice_ms, &mut next)?;
|
|
if let Some(m) = migrated.as_mut()
|
|
&& (before != Some(spec.pin) || current_cpu() != Some(spec.pin))
|
|
{
|
|
*m += 1;
|
|
}
|
|
if s.moved { dropped.push((i, s)) } else { kept.push((i, s)) }
|
|
}
|
|
let ns: Vec<f64> = kept.iter().map(|k| k.1.ns_per_call).collect();
|
|
let cyc: Vec<f64> = kept.iter().map(|k| k.1.cycles_per_call).collect();
|
|
let med = |v: &[f64], d: usize| if v.is_empty() { "null".to_owned() } else { jnum(median_of(v), d) };
|
|
let list = |v: &[(usize, Slice)]| v.iter().map(|(i, s)| slice_json(s, *i)).collect::<Vec<_>>().join(",\n ");
|
|
let json = format!(
|
|
"{{\"regime\": {}, \"copies_k\": {}, \"expert_bytes\": {}, \"copy_stride_bytes\": {}, \"working_set_bytes\": {}, \"llc_level\": {}, \"llc_bytes\": {}, \"llc_source\": {}, \"working_set_over_llc\": {}, \"slice_ms\": {}, \"slices_requested\": {}, \"slices_kept\": {}, \"dropped_count\": {}, \"selfcheck_bitwise_equal_first_call\": {}, \"migrated_slices\": {}, \"median_ns_per_call\": {}, \"median_cycles_per_call\": {},\n \"slices\": [\n {}],\n \"dropped\": [\n {}]}}",
|
|
jstr(spec.label),
|
|
spec.copies.len(),
|
|
spec.expert_bytes,
|
|
spec.stride,
|
|
spec.expert_bytes * spec.copies.len(),
|
|
spec.llc.level,
|
|
spec.llc.bytes,
|
|
jstr(&spec.llc.source),
|
|
spec.copies.len() > 1,
|
|
jnum(spec.slice_ms, 1),
|
|
spec.slices,
|
|
kept.len(),
|
|
dropped.len(),
|
|
spec.selfcheck,
|
|
migrated.map_or("null".to_owned(), |m| m.to_string()),
|
|
med(&ns, 3),
|
|
med(&cyc, 1),
|
|
list(&kept),
|
|
list(&dropped)
|
|
);
|
|
Ok(RegimeRun { json, kept: kept.len(), ok: !kept.is_empty() && migrated.is_none_or(|m| m == 0) })
|
|
}
|
|
|
|
fn f32_bits_sha(values: &[f32]) -> String {
|
|
let mut b = Vec::with_capacity(values.len() * 4);
|
|
for v in values {
|
|
b.extend_from_slice(&v.to_bits().to_le_bytes());
|
|
}
|
|
sha_hex(&b)
|
|
}
|
|
|
|
/// `kernel_ab time ...`: one fresh process, one case, the resident and the streamed regime, JSON written by tmp + rename. Exit codes as
|
|
/// `kab time`: 0 ok; 1 usage / refused input; 3 a regime kept no slice or a slice migrated off the pin; 4 the final output differs.
|
|
fn cmd_time(args: &[String]) -> Result<ExitCode, String> {
|
|
let t = parse_time_args(args)?;
|
|
let wall0 = mono_ns();
|
|
// pin first (before any buffer or pool exists, so the pool's threads inherit the mask), then the facts about the pin
|
|
if rust_topology::pin_current_thread(t.pin as i32) < 0 {
|
|
return Err(format!("the pin to CPU {} was refused", t.pin));
|
|
}
|
|
if cfg!(target_os = "linux") && current_cpu() != Some(t.pin) {
|
|
return Err(format!("the process is not running on CPU {} after the pin", t.pin));
|
|
}
|
|
let cpu_dir = format!("/sys/devices/system/cpu/cpu{}", t.pin);
|
|
let sib_text = read_text(&format!("{cpu_dir}/topology/thread_siblings_list"));
|
|
let sibling = parse_cpu_list(&sib_text).into_iter().rfind(|c| *c != t.pin);
|
|
let sib0 = sibling.and_then(proc_stat_cpu);
|
|
let pin0 = proc_stat_cpu(t.pin);
|
|
let load0 = read_text("/proc/loadavg");
|
|
|
|
// the case: the KAB1 reader rule (validate, then use) and the manifest and case input hashes
|
|
let (manifest_bytes, _provenance, cases, _files) = read_manifest(&t.dir).map_err(|e| e.to_string())?;
|
|
let manifest_sha = sha_hex(&manifest_bytes);
|
|
let entry = cases.iter().find(|c| c.id == t.case).ok_or_else(|| format!("case {} is not in the manifest", t.case))?;
|
|
let case = read_case_in(&t.dir, entry).map_err(|e| e.to_string())?;
|
|
let header = case.header;
|
|
let weights = &case.blob[IN_HEADER..header.input_at()];
|
|
let expert_bytes = weights.len();
|
|
|
|
// environment and tree
|
|
let env = managed_env_now();
|
|
let report = cpu_kernel_report();
|
|
let tree = family_of(&report).ok_or("no process kernel family line in cpu_kernel_report")?;
|
|
|
|
// the streamed set: K copies, K x stride at least 2 x the last-level cache of the pinned CPU (the design choice of kab_time.cpp)
|
|
let llc = match (t.llc_bytes, llc_of_cpu(t.pin)) {
|
|
(Some(bytes), found) => Llc { level: found.map_or(0, |l| l.level), bytes, source: "--llc-bytes (override)".to_owned() },
|
|
(None, Some(l)) => l,
|
|
(None, None) => return Err(format!("cannot read the last-level cache size of CPU {} from sysfs; pass --llc-bytes", t.pin)),
|
|
};
|
|
if llc.bytes == 0 {
|
|
return Err("--llc-bytes must be positive".to_owned());
|
|
}
|
|
let stride = expert_bytes.div_ceil(ALIGN) * ALIGN;
|
|
let copies_k = ((2 * llc.bytes) / stride as u64) as usize + 1;
|
|
if copies_k * stride > (4usize << 30) {
|
|
return Err("the streamed working set would exceed 4 GiB; check --llc-bytes".to_owned());
|
|
}
|
|
|
|
// the pool is created AFTER the pin: its worker inherits the one-CPU mask (rust_platform::cores sees a one-CPU affinity)
|
|
let mut pool = DirectCpuPool::new(1).map_err(|e| format!("DirectCpuPool::new(1) failed: {e:?}"))?;
|
|
let want = compute_case(&mut pool, &case)?;
|
|
let want_bits: Vec<u32> = want.iter().map(|v| v.to_bits()).collect();
|
|
let output_sha = f32_bits_sha(&want);
|
|
|
|
let mut tokens = Arena::<f32>::new(header.rows * H);
|
|
tokens.slice_mut(header.rows * H).copy_from_slice(&case.input());
|
|
let mut resident = Arena::<u8>::new(stride);
|
|
resident.slice_mut(expert_bytes).copy_from_slice(weights);
|
|
let mut streamed = Arena::<u8>::new(stride * copies_k);
|
|
for k in 0..copies_k {
|
|
streamed.slice_mut(stride * copies_k)[k * stride..k * stride + expert_bytes].copy_from_slice(weights);
|
|
}
|
|
let res_copies: Vec<&[u8]> = vec![resident.slice(expert_bytes)];
|
|
let stm_all = streamed.slice(stride * copies_k);
|
|
let stm_copies: Vec<&[u8]> = (0..copies_k).map(|k| &stm_all[k * stride..k * stride + expert_bytes]).collect();
|
|
|
|
let mut timed = Timed {
|
|
pool,
|
|
gu: gate_up_row(header.gu).ok_or("gate/up type")?.1,
|
|
down: down_row(header.down).ok_or("down type")?.1,
|
|
header,
|
|
pairs: (0..header.rows).map(|r| (r, 0)).collect(),
|
|
tokens: tokens.slice(header.rows * H),
|
|
out: vec![0.0f32; header.rows * H],
|
|
};
|
|
// selfcheck: the timed call's output on every aligned copy is bit-identical to the first (unaligned) call's
|
|
let mut selfcheck = true;
|
|
for w in [res_copies[0], stm_copies[0], stm_copies[copies_k - 1]] {
|
|
timed.call(w)?;
|
|
selfcheck &= timed.out.iter().map(|v| v.to_bits()).eq(want_bits.iter().copied());
|
|
}
|
|
if !selfcheck {
|
|
return Err("selfcheck failed: the timed call differs from the first call".to_owned());
|
|
}
|
|
|
|
let ghz0 = core_ghz();
|
|
let mut regimes = Vec::new();
|
|
let mut all_ok = true;
|
|
let (mut kept_res, mut kept_stm) = (0, 0);
|
|
for (label, copies, sel) in [("RESIDENT", &res_copies, RegimeSel::Resident), ("STREAMED", &stm_copies, RegimeSel::Streamed)] {
|
|
if t.regime != RegimeSel::Both && t.regime != sel {
|
|
continue;
|
|
}
|
|
let spec = RegimeSpec { label, copies: copies.clone(), expert_bytes, stride, llc: &llc, slices: t.slices, slice_ms: t.slice_ms, pin: t.pin, selfcheck };
|
|
let r = run_regime(&mut timed, &spec)?;
|
|
all_ok &= r.ok;
|
|
if sel == RegimeSel::Resident { kept_res = r.kept } else { kept_stm = r.kept }
|
|
regimes.push(r.json);
|
|
}
|
|
let ghz1 = core_ghz();
|
|
timed.call(res_copies[0])?;
|
|
let final_same = timed.out.iter().map(|v| v.to_bits()).eq(want_bits.iter().copied());
|
|
|
|
let threads = observed_threads();
|
|
let sib1 = sibling.and_then(proc_stat_cpu);
|
|
let pin1 = proc_stat_cpu(t.pin);
|
|
let frac = |f: Option<f64>| f.map_or("null".to_owned(), |v| jnum(v, 4));
|
|
let rust_fmt = |l: &str| jstr(l);
|
|
let (gu_name, down_name) = (gate_up_row(header.gu).map_or("?", |x| x.4), down_row(header.down).map_or("?", |x| x.4));
|
|
let in_name = format!("case-{}.in", t.case);
|
|
let command_line = format!(
|
|
"time --run-dir {} --case {} --slices {} --pin {} --out {}{}{}",
|
|
t.dir.display(),
|
|
t.case,
|
|
t.slices,
|
|
t.pin,
|
|
t.out.display(),
|
|
if args.iter().any(|a| a == "--slice-ms") { format!(" --slice-ms {}", t.slice_ms) } else { String::new() },
|
|
match t.regime {
|
|
RegimeSel::Both => String::new(),
|
|
RegimeSel::Resident => " --regime resident".to_owned(),
|
|
RegimeSel::Streamed => " --regime streamed".to_owned(),
|
|
}
|
|
);
|
|
let mut j = String::from("{\n \"format\": \"KAB1-time\",\n \"version\": 1,\n \"mode\": \"time\",\n \"writer\": \"rust\",\n");
|
|
j += &format!(" \"command_line\": {},\n \"run_dir\": {},\n \"manifest_sha256\": {},\n", jstr(&command_line), jstr(&t.dir.display().to_string()), jstr(&manifest_sha));
|
|
j += &format!(
|
|
" \"case\": {{\"id\": {}, \"gu_type\": {}, \"down_type\": {}, \"gu_name\": {}, \"down_name\": {}, \"rows\": {}, \"input_file\": {}, \"input_sha256\": {}, \"input_sha256_matches_manifest\": true, \"expert_bytes\": {}}},\n",
|
|
jstr(&t.case),
|
|
header.gu,
|
|
header.down,
|
|
jstr(gu_name),
|
|
jstr(down_name),
|
|
header.rows,
|
|
jstr(&in_name),
|
|
jstr(&entry.in_sha256),
|
|
expert_bytes
|
|
);
|
|
j += &format!(
|
|
" \"tree\": {},\n \"tree_detail\": {{\"tree\": {}, \"cpu_report\": [{}], \"strata_env\": {}}},\n \"effective_env\": {},\n",
|
|
jstr(tree),
|
|
jstr(tree),
|
|
report.iter().map(|l| rust_fmt(l)).collect::<Vec<_>>().join(", "),
|
|
json_env(&env),
|
|
json_env(&env)
|
|
);
|
|
j += &format!(
|
|
" \"pool\": {{\"workers\": 1, \"host_drains\": true, \"threads_observed\": [{}], \"note\": \"DirectCpuPool::new(1): one worker thread plus the calling thread that drains beside it (pool.cpp host_works_); both inherit the one-CPU mask of the pin\"}},\n",
|
|
threads.iter().map(|(n, c)| format!("{{\"name\": {}, \"cpu\": {}}}", jstr(n), c.map_or("null".to_owned(), |c| c.to_string()))).collect::<Vec<_>>().join(", ")
|
|
);
|
|
j += &format!(
|
|
" \"pin\": {{\"cpu\": {}, \"thread_siblings_list\": {}, \"sibling_cpu\": {}, \"physical_core_id\": {}, \"pin_busy_fraction_during_run\": {}, \"sibling_busy_fraction_during_run\": {}, \"sibling_busy_note\": \"/proc/stat jiffies of the sibling logical CPU between the start and the end of this process; it is recorded, no threshold is applied here\", \"scaling_governor\": {}, \"cpufreq_boost\": {}, \"loadavg_start\": {}, \"loadavg_end\": {}, \"final_cpu\": {}}},\n",
|
|
t.pin,
|
|
jstr(&sib_text),
|
|
sibling.map_or("null".to_owned(), |s| s.to_string()),
|
|
jstr(&read_text(&format!("{cpu_dir}/topology/core_id"))),
|
|
frac(busy_fraction(pin0, pin1)),
|
|
if sibling.is_some() { frac(busy_fraction(sib0, sib1)) } else { "null".to_owned() },
|
|
jstr(&read_text(&format!("{cpu_dir}/cpufreq/scaling_governor"))),
|
|
jstr(&read_text("/sys/devices/system/cpu/cpufreq/boost")),
|
|
jstr(&load0),
|
|
jstr(&read_text("/proc/loadavg")),
|
|
current_cpu().map_or("null".to_owned(), |c| c.to_string())
|
|
);
|
|
j += &format!(" \"buffers\": {{\"alignment_bytes\": {ALIGN}, \"expert_copy_stride_bytes\": {stride}, \"activations_aligned\": true, \"scratch_aligned\": false, \"scratch_note\": \"the pool's own scratch is allocated inside the crate\"}},\n");
|
|
j += &format!(
|
|
" \"clock_calibration\": {{\"method\": {}, \"source\": \"engine/strata/src/kernels/cpu/tq_cpu_parity.cpp --bench: core_ghz() lines 273-284, time_slice() lines 290-304; the dependent-add chain needs inline assembly, so the safe Rust twin chains multiplies\", \"drop_rule\": {{\"source_file\": \"engine/strata/src/kernels/cpu/tq_cpu_parity.cpp\", \"source_line\": 303, \"source_text\": \"std::fabs(g1 - g0) > 0.05 * g0\", \"fraction\": {}, \"meaning\": \"a slice whose calibrated clock moved by more than 5 percent between its before and after calibration is dropped\"}}, \"slice_ms_source\": \"tq_cpu_parity.cpp:461 slice_ms = quick ? 40 : 60\", \"ghz_at_start\": {}, \"ghz_at_end\": {}, \"tsc_invariant\": null, \"clocks\": \"monotonic ns (std::time::Instant); no TSC read: rdtsc and lfence are unsafe intrinsics and the crate keeps unsafe_code = deny\"}},\n",
|
|
jstr(CLOCK_METHOD),
|
|
jnum(CLOCK_MOVED_FRACTION, 2),
|
|
jnum(ghz0, 6),
|
|
jnum(ghz1, 6)
|
|
);
|
|
j += &format!(
|
|
" \"build\": {{\"profile\": {}, \"rustflags\": {}, \"example\": \"crates/native-cpu-expert/examples/kernel_ab.rs\"}},\n",
|
|
jstr(if cfg!(debug_assertions) { "dev" } else { "release" }),
|
|
jstr(&std::env::var("RUSTFLAGS").unwrap_or_default())
|
|
);
|
|
j += &format!(
|
|
" \"selfcheck_bitwise_equal_first_call\": {selfcheck},\n \"final_output_unchanged\": {final_same},\n \"output_sha256\": {},\n \"duration_ns\": {},\n \"timing_caveat\": \"numbers from a shared host are not evidence by themselves; loadavg and the sibling busy fraction are recorded above\",\n \"regimes\": [\n {}\n ]\n}}\n",
|
|
jstr(&output_sha),
|
|
mono_ns() - wall0,
|
|
regimes.join(",\n ")
|
|
);
|
|
let tmp = PathBuf::from(format!("{}.tmp", t.out.display()));
|
|
fs::write(&tmp, j.as_bytes()).map_err(|e| format!("{}: {e}", tmp.display()))?;
|
|
fs::rename(&tmp, &t.out).map_err(|e| format!("rename to {}: {e}", t.out.display()))?;
|
|
println!("kernel_ab time: case={} tree={tree} pin={} slices={} resident_kept={kept_res} streamed_kept={kept_stm} K={copies_k} out={}", t.case, t.pin, t.slices, t.out.display());
|
|
if !all_ok {
|
|
eprintln!("kernel_ab time: a regime has no kept slice or a slice migrated off CPU {}", t.pin);
|
|
return Ok(ExitCode::from(3));
|
|
}
|
|
if !final_same {
|
|
eprintln!("kernel_ab time: the final output differs from the first call's");
|
|
return Ok(ExitCode::from(4));
|
|
}
|
|
Ok(ExitCode::SUCCESS)
|
|
}
|
|
|
|
// ------------------------------------------------------------------------------------------------ alternate: cells, environment, schedule
|
|
|
|
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
|
|
enum Impl {
|
|
Cpp,
|
|
Rust,
|
|
}
|
|
impl Impl {
|
|
fn name(self) -> &'static str {
|
|
match self {
|
|
Impl::Cpp => "cpp",
|
|
Impl::Rust => "rust",
|
|
}
|
|
}
|
|
}
|
|
|
|
/// One process of a round: an implementation, a tree and a replicate (`a` is the A/B process, `b` the A/A twin).
|
|
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
|
|
struct Proc {
|
|
imp: Impl,
|
|
tree: &'static str,
|
|
rep: char,
|
|
}
|
|
impl Proc {
|
|
fn name(&self) -> String {
|
|
format!("{}-{}-{}", self.imp.name(), self.tree, self.rep)
|
|
}
|
|
fn parse(s: &str) -> Option<Proc> {
|
|
let mut p = s.split('-');
|
|
let imp = match p.next()? {
|
|
"cpp" => Impl::Cpp,
|
|
"rust" => Impl::Rust,
|
|
_ => return None,
|
|
};
|
|
let wanted = p.next()?;
|
|
let tree = *TREES.iter().find(|t| **t == wanted)?;
|
|
let rep = match p.next()? {
|
|
"a" => 'a',
|
|
"b" => 'b',
|
|
_ => return None,
|
|
};
|
|
p.next().is_none().then_some(Proc { imp, tree, rep })
|
|
}
|
|
}
|
|
|
|
/// Every process of a round for the given trees, in canonical order.
|
|
fn procs_for(trees: &[&'static str]) -> Vec<Proc> {
|
|
let mut v = Vec::new();
|
|
for imp in [Impl::Cpp, Impl::Rust] {
|
|
for tree in trees {
|
|
for rep in ['a', 'b'] {
|
|
v.push(Proc { imp, tree, rep });
|
|
}
|
|
}
|
|
}
|
|
v
|
|
}
|
|
|
|
/// The environment a cell needs and nothing else. The avx2 trees set `STRATA_FORCE_AVX2=1`, which both implementations honour. The
|
|
/// Rust cells run `DirectCpuPool::new(1)`, a worker thread plus the draining caller, both confined to the one pinned CPU: the pool must
|
|
/// not re-pin its caller (`LELEKA_CPU_POOL_PIN_HOST=off`, so the pin is the requested one) and its worker must not spin after a batch
|
|
/// (`STRATA_POOL_SPIN_US=0`; with the 20 ms default the worker spins on the caller's only CPU and costs it half its time).
|
|
fn cell_env(p: &Proc) -> Vec<(String, String)> {
|
|
let mut v = Vec::new();
|
|
if p.tree == "avx2" {
|
|
v.push(("STRATA_FORCE_AVX2".to_owned(), "1".to_owned()));
|
|
}
|
|
if p.imp == Impl::Rust {
|
|
v.push(("LELEKA_CPU_POOL_PIN_HOST".to_owned(), "off".to_owned()));
|
|
v.push(("STRATA_POOL_SPIN_US".to_owned(), "0".to_owned()));
|
|
}
|
|
v.sort();
|
|
v
|
|
}
|
|
|
|
/// A command whose environment is exactly: the parent's variables minus every STRATA_* / LELEKA_* one, plus the cell's variables.
|
|
fn scrubbed_command(program: &Path, parent_env: &[(OsString, OsString)], cell: &[(String, String)]) -> Command {
|
|
let mut c = Command::new(program);
|
|
c.env_clear();
|
|
for (k, v) in parent_env {
|
|
if !is_managed_name(&k.to_string_lossy()) {
|
|
c.env(k, v);
|
|
}
|
|
}
|
|
for (k, v) in cell {
|
|
c.env(k, v);
|
|
}
|
|
c
|
|
}
|
|
|
|
/// Runs a prepared cell command; a failure names the cell.
|
|
fn run_cell(cmd: &mut Command, cell: &str) -> Result<std::process::Output, String> {
|
|
let out = cmd.output().map_err(|e| format!("cell {cell}: cannot start the process: {e}"))?;
|
|
if out.status.success() {
|
|
return Ok(out);
|
|
}
|
|
let tail = |b: &[u8]| String::from_utf8_lossy(b).lines().rev().take(3).collect::<Vec<_>>().into_iter().rev().collect::<Vec<_>>().join(" | ");
|
|
Err(format!("cell {cell} failed ({}): stderr: {}; stdout: {}", out.status.code().map_or("killed by a signal".to_owned(), |c| format!("exit {c}")), tail(&out.stderr), tail(&out.stdout)))
|
|
}
|
|
|
|
fn splitmix(state: &mut u64) -> u64 {
|
|
*state = state.wrapping_add(0x9E37_79B9_7F4A_7C15);
|
|
let mut z = *state;
|
|
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
|
|
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
|
|
z ^ (z >> 31)
|
|
}
|
|
|
|
/// The schedule of one batch: round `i` (0-based) rotates a seeded permutation by `i mod n`; every block of `n` rounds draws a fresh
|
|
/// permutation, so each process takes each position equally often within a block. A pure function of (seed, batch, rounds, procs).
|
|
fn make_schedule(seed: u64, batch: u32, rounds: u32, procs: &[Proc]) -> Vec<Vec<Proc>> {
|
|
let n = procs.len();
|
|
let mut out = Vec::new();
|
|
let mut base: Vec<Proc> = Vec::new();
|
|
for i in 0..rounds as usize {
|
|
if i % n == 0 {
|
|
let mut st = seed;
|
|
for x in [u64::from(batch), (i / n) as u64] {
|
|
st = st.wrapping_add(x.wrapping_mul(0x9E37_79B9_7F4A_7C15));
|
|
st = splitmix(&mut st);
|
|
}
|
|
base = procs.to_vec();
|
|
for j in (1..n).rev() {
|
|
let k = (splitmix(&mut st) % (j as u64 + 1)) as usize;
|
|
base.swap(j, k);
|
|
}
|
|
}
|
|
let mut order = base.clone();
|
|
order.rotate_left(i % n);
|
|
out.push(order);
|
|
}
|
|
out
|
|
}
|
|
|
|
const SCHEDULE_MAGIC: &str = "# KAB1-alt schedule v1";
|
|
|
|
fn schedule_text(seed: u64, batch: u32, rounds: u32, case: &str, pin: usize, first_round: u32, order: &[Vec<Proc>]) -> String {
|
|
let mut t = format!("{SCHEDULE_MAGIC} (written before the first run; the runner reads this file back)\n# seed={seed} batch={batch} rounds={rounds} case={case} pin={pin}\n");
|
|
for (i, o) in order.iter().enumerate() {
|
|
t += &format!("{}\t{}\n", first_round + i as u32, o.iter().map(Proc::name).collect::<Vec<_>>().join(","));
|
|
}
|
|
t
|
|
}
|
|
|
|
/// Reads a schedule back: (round number, processes in order) per round. Every round must name each process of the first round once.
|
|
fn parse_schedule(text: &str) -> Result<Vec<(u32, Vec<Proc>)>, String> {
|
|
let mut lines = text.lines();
|
|
if !lines.next().is_some_and(|l| l.starts_with(SCHEDULE_MAGIC)) {
|
|
return Err("not a KAB1-alt schedule".to_owned());
|
|
}
|
|
let mut rounds: Vec<(u32, Vec<Proc>)> = Vec::new();
|
|
for l in lines.filter(|l| !l.starts_with('#') && !l.is_empty()) {
|
|
let (no, list) = l.split_once('\t').ok_or_else(|| format!("bad schedule line {l:?}"))?;
|
|
let no = no.parse::<u32>().map_err(|_| format!("bad round number in {l:?}"))?;
|
|
let order: Vec<Proc> = list.split(',').map(|n| Proc::parse(n).ok_or_else(|| format!("unknown process {n:?} in the schedule"))).collect::<Result<_, _>>()?;
|
|
if let Some(prev) = rounds.last()
|
|
&& (no != prev.0 + 1 || BTreeSet::from_iter(order.iter()) != BTreeSet::from_iter(prev.1.iter()) || order.len() != prev.1.len())
|
|
{
|
|
return Err(format!("round {no} does not follow round {} with the same processes", prev.0));
|
|
}
|
|
rounds.push((no, order));
|
|
}
|
|
if rounds.is_empty() {
|
|
return Err("the schedule has no round".to_owned());
|
|
}
|
|
Ok(rounds)
|
|
}
|
|
|
|
/// Refuses a path that is, or lies inside, a Git checkout (generated artifacts stay out of Git).
|
|
fn inside_git_checkout(path: &Path) -> bool {
|
|
let abs = std::path::absolute(path).unwrap_or_else(|_| path.to_path_buf());
|
|
abs.ancestors().any(|a| a.join(".git").exists())
|
|
}
|
|
|
|
// ------------------------------------------------------------------------------------------------ alternate: reading a process's JSON
|
|
|
|
#[derive(Debug, Clone)]
|
|
struct RegimeStat {
|
|
copies_k: usize,
|
|
expert_bytes: usize,
|
|
llc_bytes: u64,
|
|
requested: usize,
|
|
dropped: usize,
|
|
median_ns: f64,
|
|
median_cycles: f64,
|
|
ns: Vec<f64>,
|
|
cycles: Vec<f64>,
|
|
max_drift: f64,
|
|
selfcheck: bool,
|
|
}
|
|
|
|
#[derive(Debug, Clone)]
|
|
struct ProcOut {
|
|
proc: Proc,
|
|
regimes: BTreeMap<String, RegimeStat>,
|
|
ghz_start: f64,
|
|
ghz_end: f64,
|
|
/// None: unknown; Some(true): the sibling was idle (or there is none) under the 5 percent rule.
|
|
sibling_idle: Option<bool>,
|
|
final_unchanged: bool,
|
|
output_sha: Option<String>,
|
|
tree_text: String,
|
|
cpu_model: Option<String>,
|
|
}
|
|
|
|
/// What a process's JSON must say about the run that produced it.
|
|
struct Expect<'a> {
|
|
manifest_sha: &'a str,
|
|
input_sha: &'a str,
|
|
case: &'a str,
|
|
pin: usize,
|
|
}
|
|
|
|
fn parse_regime(r: &Json, imp: Impl) -> Result<RegimeStat, String> {
|
|
let mut ns = Vec::new();
|
|
let mut cycles = Vec::new();
|
|
let mut max_drift = 0.0f64;
|
|
for (key, keep) in [("slices", true), ("dropped", false)] {
|
|
for s in r.array(key)? {
|
|
let (g0, g1) = (s.float("ghz_before")?, s.float("ghz_after")?);
|
|
if g0 > 0.0 {
|
|
max_drift = max_drift.max(((g1 - g0).abs() / g0).min(1.0));
|
|
}
|
|
if keep {
|
|
ns.push(s.float("ns_per_call")?);
|
|
cycles.push(s.float("cycles_per_call")?);
|
|
}
|
|
}
|
|
}
|
|
let selfcheck_key = if imp == Impl::Cpp { "selfcheck_bitwise_equal_compose_expert" } else { "selfcheck_bitwise_equal_first_call" };
|
|
let kept = r.uint("slices_kept")? as usize;
|
|
if kept != ns.len() || kept == 0 {
|
|
return Err(format!("slices_kept {kept} disagrees with the {} kept slices (or none was kept)", ns.len()));
|
|
}
|
|
Ok(RegimeStat {
|
|
copies_k: r.uint("copies_k")? as usize,
|
|
expert_bytes: r.uint("expert_bytes")? as usize,
|
|
llc_bytes: r.uint("llc_bytes")?,
|
|
requested: r.uint("slices_requested")? as usize,
|
|
dropped: r.uint("dropped_count")? as usize,
|
|
median_ns: r.float("median_ns_per_call")?,
|
|
median_cycles: r.float("median_cycles_per_call")?,
|
|
ns,
|
|
cycles,
|
|
max_drift,
|
|
selfcheck: r.flag(selfcheck_key)?,
|
|
})
|
|
}
|
|
|
|
fn describe_cpp_tree(d: &Json) -> String {
|
|
let b = |k: &str| d.get(k).map_or("?".to_owned(), |v| match v {
|
|
Json::Bool(x) => x.to_string(),
|
|
Json::Num(n) => n.clone(),
|
|
_ => "?".to_owned(),
|
|
});
|
|
let env = match d.get("strata_env") {
|
|
Some(Json::Obj(items)) if !items.is_empty() => items.iter().map(|(k, v)| format!("{k}={}", if let Json::Str(s) = v { s.as_str() } else { "?" })).collect::<Vec<_>>().join(" "),
|
|
_ => "no STRATA_* variable set (STRATA_NO_IQ512, STRATA_NO_IQ256 and STRATA_IQ_GATHER unset)".to_owned(),
|
|
};
|
|
format!("avx2_ok={} avx512_ok={} iq512_gather_on={} iq256_gather_setting={}; {env}", b("avx2_ok"), b("avx512_ok"), b("iq512_gather_on"), b("iq256_gather_setting"))
|
|
}
|
|
|
|
/// Parses a process's KAB1-time JSON and checks it against the cell that was started: writer, tree, manifest and input hashes, case,
|
|
/// pin, and that the effective STRATA_* / LELEKA_* environment is exactly the cell's.
|
|
fn parse_proc_json(p: &Proc, bytes: &[u8], expect: &Expect) -> Result<ProcOut, String> {
|
|
let j = parse_json(bytes)?;
|
|
let name = p.name();
|
|
let fail = |what: String| format!("cell {name}: {what}");
|
|
if j.str("format").map_err(fail)? != "KAB1-time" || j.uint("version").map_err(fail)? != 1 {
|
|
return Err(fail("the output is not KAB1-time version 1".to_owned()));
|
|
}
|
|
if j.str("writer").map_err(fail)? != p.imp.name() {
|
|
return Err(fail(format!("the output's writer is {:?}, expected {}", j.str("writer").unwrap_or("?"), p.imp.name())));
|
|
}
|
|
if j.str("tree").map_err(fail)? != p.tree {
|
|
return Err(fail(format!("the process ran the {} tree, the cell asks for {}", j.str("tree").unwrap_or("?"), p.tree)));
|
|
}
|
|
if j.str("manifest_sha256").map_err(fail)? != expect.manifest_sha {
|
|
return Err(fail("manifest_sha256 differs from the run directory's".to_owned()));
|
|
}
|
|
let c = j.req("case").map_err(fail)?;
|
|
if c.str("id").map_err(fail)? != expect.case || c.str("input_sha256").map_err(fail)? != expect.input_sha {
|
|
return Err(fail("the case id or its input hash differs from the manifest's".to_owned()));
|
|
}
|
|
let pin = j.req("pin").map_err(fail)?;
|
|
if pin.uint("cpu").map_err(fail)? as usize != expect.pin {
|
|
return Err(fail(format!("pinned to CPU {}, expected {}", pin.uint("cpu").unwrap_or(u64::MAX), expect.pin)));
|
|
}
|
|
let want_env: BTreeMap<String, String> = cell_env(p).into_iter().collect();
|
|
let mut seen_env = BTreeMap::new();
|
|
if let Json::Obj(items) = j.req("effective_env").map_err(fail)? {
|
|
for (k, v) in items {
|
|
seen_env.insert(k.clone(), match v {
|
|
Json::Str(s) => s.clone(),
|
|
Json::Num(n) => n.clone(),
|
|
_ => "?".to_owned(),
|
|
});
|
|
}
|
|
}
|
|
if seen_env != want_env {
|
|
return Err(fail(format!("effective environment {seen_env:?} differs from the cell's {want_env:?}")));
|
|
}
|
|
let mut regimes = BTreeMap::new();
|
|
for r in j.array("regimes").map_err(fail)? {
|
|
let label = r.str("regime").map_err(fail)?.to_owned();
|
|
regimes.insert(label, parse_regime(r, p.imp).map_err(fail)?);
|
|
}
|
|
for want in ["RESIDENT", "STREAMED"] {
|
|
if !regimes.contains_key(want) {
|
|
return Err(fail(format!("regime {want} is missing")));
|
|
}
|
|
}
|
|
let clock = j.req("clock_calibration").map_err(fail)?;
|
|
let sibling_idle = match pin.req("sibling_cpu").map_err(fail)? {
|
|
Json::Null => Some(true),
|
|
_ => pin.float_or_null("sibling_busy_fraction_during_run").map_err(fail)?.map(|f| f < SIBLING_BUSY_LIMIT),
|
|
};
|
|
let detail = j.req("tree_detail").map_err(fail)?;
|
|
let (tree_text, cpu_report) = if p.imp == Impl::Rust {
|
|
let report: Vec<String> = detail.array("cpu_report").map_err(fail)?.iter().filter_map(|l| if let Json::Str(s) = l { Some(s.clone()) } else { None }).collect();
|
|
let line = report.iter().find(|l| l.starts_with("cpu: process kernel family")).cloned().ok_or_else(|| fail("no process kernel family line".to_owned()))?;
|
|
(format!("leleka-serve {line}"), report)
|
|
} else {
|
|
(describe_cpp_tree(detail), Vec::new())
|
|
};
|
|
let cpu_model = (!cpu_report.is_empty()).then(|| cpu_model_of(&cpu_report));
|
|
Ok(ProcOut {
|
|
proc: *p,
|
|
regimes,
|
|
ghz_start: clock.float("ghz_at_start").map_err(fail)?,
|
|
ghz_end: clock.float("ghz_at_end").map_err(fail)?,
|
|
sibling_idle,
|
|
final_unchanged: j.flag("final_output_unchanged").map_err(fail)?,
|
|
output_sha: j.get("output_sha256").and_then(|v| if let Json::Str(s) = v { Some(s.clone()) } else { None }),
|
|
tree_text,
|
|
cpu_model,
|
|
})
|
|
}
|
|
|
|
// ------------------------------------------------------------------------------------------------ alternate: round records
|
|
|
|
struct Tool {
|
|
compiler: String,
|
|
version: String,
|
|
triple: String,
|
|
flags: String,
|
|
}
|
|
|
|
struct SideStat {
|
|
median: f64,
|
|
p05: f64,
|
|
p95: f64,
|
|
}
|
|
|
|
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
|
enum Kind {
|
|
Ab,
|
|
AaCpp,
|
|
AaRust,
|
|
}
|
|
impl Kind {
|
|
fn slug(self) -> &'static str {
|
|
match self {
|
|
Kind::Ab => "ab",
|
|
Kind::AaCpp => "aa-cpp",
|
|
Kind::AaRust => "aa-rust",
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Everything a round record needs that does not change within a batch.
|
|
struct BatchCtx<'a> {
|
|
verified: &'a Verified,
|
|
case: &'a CaseEntry,
|
|
pin: usize,
|
|
machine_role: String,
|
|
os: String,
|
|
cpu_model: String,
|
|
started_utc: String,
|
|
rust_tool: Tool,
|
|
batch: u32,
|
|
/// Equality of our tree against the C++ reference per tree, from the equality phase.
|
|
equality: &'a BTreeMap<&'static str, Outcome>,
|
|
}
|
|
|
|
fn side_stat(r: &RegimeStat, cycles: bool) -> SideStat {
|
|
let v = if cycles { &r.cycles } else { &r.ns };
|
|
SideStat { median: if cycles { r.median_cycles } else { r.median_ns }, p05: percentile_of(v, 0.05), p95: percentile_of(v, 0.95) }
|
|
}
|
|
|
|
fn stat_json(s: &SideStat) -> String {
|
|
format!("{{\"median\": {}, \"p05\": {}, \"p95\": {}}}", jnum(s.median, 6), jnum(s.p05, 6), jnum(s.p95, 6))
|
|
}
|
|
|
|
fn tool_json(t: &Tool) -> String {
|
|
format!("{{\"compiler\": {}, \"version\": {}, \"target_triple\": {}, \"flags\": {}}}", jstr(&t.compiler), jstr(&t.version), jstr(&t.triple), jstr(&t.flags))
|
|
}
|
|
|
|
fn equality_block(c: &CaseEntry, o: &Outcome) -> String {
|
|
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)
|
|
)
|
|
});
|
|
format!(
|
|
"{{\n \"mode\": \"{}\",\n \"verdict\": \"{}\",\n \"compared_values\": {},\n \"mismatches\": {}{tolerance}\n }}",
|
|
if c.tolerance.is_some() { "tolerance" } else { "bitwise" },
|
|
if o.equal() { "EQUAL" } else { "NOT_EQUAL" },
|
|
o.compared,
|
|
o.mismatches
|
|
)
|
|
}
|
|
|
|
/// The A/A equality: the same implementation in two fresh processes. Rust: the output hashes of the two processes (and each one's
|
|
/// selfcheck); C++: each process's timed composition equals `compose_expert()` bit for bit (selfcheck), which is the same function.
|
|
fn aa_outcome(a: &ProcOut, b: &ProcOut, rows: usize) -> (Outcome, String) {
|
|
let compared = rows * H;
|
|
let selfchecks = a.regimes.values().chain(b.regimes.values()).all(|r| r.selfcheck) && a.final_unchanged && b.final_unchanged;
|
|
let same = selfchecks && (a.proc.imp == Impl::Cpp || (a.output_sha.is_some() && a.output_sha == b.output_sha));
|
|
let note = if a.proc.imp == Impl::Cpp { "selfcheck of both processes against compose_expert()" } else { "output sha256 of both processes" };
|
|
let outcome = Outcome { compared, mismatches: usize::from(!same), differing_bits: usize::from(!same), max_abs_error: 0.0, first_mismatch: None };
|
|
(outcome, note.to_owned())
|
|
}
|
|
|
|
/// The records of one round: per tree and regime the A/B record (ours = Rust `a`, reference = C++ `a`) and the two A/A records.
|
|
fn round_records(ctx: &BatchCtx, round_no: u32, done: &[ProcOut]) -> Result<Vec<(String, String)>, String> {
|
|
let find = |imp: Impl, tree: &str, rep: char| done.iter().find(|p| p.proc.imp == imp && p.proc.tree == tree && p.proc.rep == rep).ok_or_else(|| format!("round {round_no}: process {}-{tree}-{rep} did not run", imp.name()));
|
|
let p = &ctx.verified.provenance;
|
|
let c = ctx.case;
|
|
let cpp_tool = Tool { compiler: p.compiler_id.clone(), version: p.compiler_version.clone(), triple: p.target_triple.clone(), flags: p.reference_flags.clone() };
|
|
let (gu, down) = (gate_up_row(c.gu).map_or("?", |x| x.4), down_row(c.down).map_or("?", |x| x.4));
|
|
if done.is_empty() {
|
|
return Err("empty round".to_owned());
|
|
}
|
|
let position = |p: &ProcOut| done.iter().position(|d| d.proc == p.proc).unwrap_or(0);
|
|
let mut files = Vec::new();
|
|
let trees: Vec<&'static str> = TREES.iter().copied().filter(|t| done.iter().any(|d| d.proc.tree == *t)).collect();
|
|
for tree in trees {
|
|
let (cpp_a, cpp_b, rust_a, rust_b) = (find(Impl::Cpp, tree, 'a')?, find(Impl::Cpp, tree, 'b')?, find(Impl::Rust, tree, 'a')?, find(Impl::Rust, tree, 'b')?);
|
|
for regime in ["RESIDENT", "STREAMED"] {
|
|
for kind in [Kind::Ab, Kind::AaCpp, Kind::AaRust] {
|
|
let (ours, reference, ours_tool, ref_tool) = match kind {
|
|
Kind::Ab => (rust_a, cpp_a, &ctx.rust_tool, &cpp_tool),
|
|
Kind::AaCpp => (cpp_a, cpp_b, &cpp_tool, &cpp_tool),
|
|
Kind::AaRust => (rust_a, rust_b, &ctx.rust_tool, &ctx.rust_tool),
|
|
};
|
|
let (o, r) = (&ours.regimes[regime], &reference.regimes[regime]);
|
|
if (o.copies_k, o.expert_bytes, o.llc_bytes) != (r.copies_k, r.expert_bytes, r.llc_bytes) {
|
|
return Err(format!("round {round_no} {tree} {regime}: the streamed set differs between {} and {} (K {} vs {}, LLC {} vs {})", ours.proc.name(), reference.proc.name(), o.copies_k, r.copies_k, o.llc_bytes, r.llc_bytes));
|
|
}
|
|
let (equality, equality_note) = match kind {
|
|
Kind::Ab => (equality_block(c, &ctx.equality[tree]), "Rust output against the C++ reference .out file of the run directory, from the equality phase of this batch".to_owned()),
|
|
_ => {
|
|
let (outcome, note) = aa_outcome(ours, reference, c.rows);
|
|
(aa_equality_block(&outcome), format!("{note}, the same implementation in two fresh processes"))
|
|
}
|
|
};
|
|
let kernel = format!(
|
|
"routed-expert-gate-up-down {gu}+{down} rows={} regime {regime} ROUND RECORD {} (batch {}, round {round_no}); ours-slot process {}, reference-slot process {}; tree ours: {}; tree reference: {}; equality: {equality_note}; aa_noise_floor is a PLACEHOLDER (n=1, CI 0): the A/A evaluation is S0.10b, this record carries one round's medians only",
|
|
c.rows,
|
|
match kind {
|
|
Kind::Ab => "A/B (ours = Rust, reference = C++)",
|
|
Kind::AaCpp => "A/A (C++ process a in the ours slot, C++ process b in the reference slot)",
|
|
Kind::AaRust => "A/A (Rust process a in the ours slot, Rust process b in the reference slot)",
|
|
},
|
|
ctx.batch,
|
|
ours.proc.name(),
|
|
reference.proc.name(),
|
|
ours.tree_text,
|
|
reference.tree_text
|
|
);
|
|
let drift = o.max_drift.max(r.max_drift);
|
|
// the two processes of this record, earliest first: the clock before the earlier one, after the later one
|
|
let (earlier, later) = if position(ours) <= position(reference) { (ours, reference) } else { (reference, ours) };
|
|
let sibling_idle = ours.sibling_idle == Some(true) && reference.sibling_idle == Some(true);
|
|
let streamed = if regime == "STREAMED" { format!(",\n \"streamed\": {{\"copies\": {}, \"expert_bytes\": {}, \"llc_bytes\": {}}}", o.copies_k, o.expert_bytes, o.llc_bytes) } else { String::new() };
|
|
let rowtype = |unit: &str| format!("{gu}+{down} rows={} {} [{unit}]", c.rows, regime.to_ascii_lowercase());
|
|
let json = 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\": {ot},\n \"reference\": {rt}\n }},\n \"case_id\": {cid},\n \"input_sha256\": {insha},\n \"kab1_manifest_sha256\": {msha},\n \"tree\": {{\"ours\": {tree_q}, \"reference\": {tree_q}}},\n \"regime\": {regime_q}{streamed},\n \"pin\": {{\"logical_cpu\": {pin}, \"sibling_idle\": {sib}}},\n \"strata_upstream_commit\": {commit},\n \"clock_calibration\": {{\"method\": {method}, \"ghz_before\": {g0}, \"ghz_after\": {g1}, \"max_drift_fraction\": {drift}, \"slices_total\": {total}, \"slices_dropped\": {dropped}}},\n \"rows\": [\n {{\"row_type\": {rt_ns}, \"unit\": \"ns\", \"rounds\": 1, \"ours\": {on}, \"reference\": {rn}}},\n {{\"row_type\": {rt_cy}, \"unit\": \"cycles\", \"rounds\": 1, \"ours\": {oc}, \"reference\": {rc}}}\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\": {equality}\n}}\n",
|
|
rid = jstr(&format!("kab1alt-{}-{}-b{}-r{round_no:05}-{}-{tree}-{}", ctx.verified.provenance.run_id, c.id, ctx.batch, kind.slug(), regime.to_ascii_lowercase())),
|
|
created = jstr(&now_utc()),
|
|
started = jstr(&ctx.started_utc),
|
|
role = jstr(&ctx.machine_role),
|
|
cpu = jstr(&ctx.cpu_model),
|
|
os = jstr(&ctx.os),
|
|
kernel = jstr(&kernel),
|
|
ot = tool_json(ours_tool),
|
|
rt = tool_json(ref_tool),
|
|
cid = jstr(&c.id),
|
|
insha = jstr(&c.in_sha256),
|
|
msha = jstr(&ctx.verified.manifest_sha256),
|
|
tree_q = jstr(tree),
|
|
regime_q = jstr(®ime.to_ascii_lowercase()),
|
|
pin = ctx.pin,
|
|
sib = sibling_idle,
|
|
commit = jstr(&p.engine_strata_pin),
|
|
method = jstr(&format!("{CLOCK_METHOD}; ghz_before is the ghz_at_start of the earlier process of this record ({}), ghz_after the ghz_at_end of the later one ({}); sibling_idle: the SMT sibling stayed under 5 percent busy during both processes; max_drift_fraction is the largest |g1 - g0| / g0 over every slice of the two processes of this record, slices_total and slices_dropped count their requested and dropped slices", earlier.proc.name(), later.proc.name())),
|
|
g0 = jnum(earlier.ghz_start, 6),
|
|
g1 = jnum(later.ghz_end, 6),
|
|
drift = jnum(drift, 6),
|
|
total = o.requested + r.requested,
|
|
dropped = o.dropped + r.dropped,
|
|
rt_ns = jstr(&rowtype("ns")),
|
|
rt_cy = jstr(&rowtype("cycles")),
|
|
on = stat_json(&side_stat(o, false)),
|
|
rn = stat_json(&side_stat(r, false)),
|
|
oc = stat_json(&side_stat(o, true)),
|
|
rc = stat_json(&side_stat(r, true)),
|
|
);
|
|
files.push((format!("r{round_no:05}.{}.{tree}.{}.json", kind.slug(), regime.to_ascii_lowercase()), json));
|
|
}
|
|
}
|
|
}
|
|
Ok(files)
|
|
}
|
|
|
|
fn aa_equality_block(o: &Outcome) -> String {
|
|
format!("{{\n \"mode\": \"bitwise\",\n \"verdict\": \"{}\",\n \"compared_values\": {},\n \"mismatches\": {}\n }}", if o.equal() { "EQUAL" } else { "NOT_EQUAL" }, o.compared, o.mismatches)
|
|
}
|
|
|
|
// ------------------------------------------------------------------------------------------------ alternate: the runner
|
|
|
|
const ALT_FLAGS: [&str; 13] = ["run-dir", "case", "rounds", "batch", "pin", "schedule", "seed", "out", "slices", "slice-ms", "llc-bytes", "machine-role", "kab"];
|
|
|
|
#[derive(Debug)]
|
|
struct AltArgs {
|
|
dir: PathBuf,
|
|
case: String,
|
|
rounds: u32,
|
|
batch: u32,
|
|
pin: usize,
|
|
schedule: PathBuf,
|
|
seed: u64,
|
|
out: Option<PathBuf>,
|
|
slices: usize,
|
|
slice_ms: Option<f64>,
|
|
llc_bytes: Option<u64>,
|
|
machine_role: Option<String>,
|
|
kab: Option<PathBuf>,
|
|
}
|
|
|
|
fn parse_alt_args(args: &[String]) -> Result<AltArgs, String> {
|
|
let f = Flags::parse(args, &ALT_FLAGS)?;
|
|
let rounds = f.number::<u32>("rounds")?.ok_or("--rounds is required")?;
|
|
let batch = f.number::<u32>("batch")?.ok_or("--batch is required")?;
|
|
if !(1..=10_000).contains(&rounds) || !(1..=1000).contains(&batch) {
|
|
return Err("--rounds must be 1..10000 and --batch 1..1000 (the batch number, counted from 1)".to_owned());
|
|
}
|
|
let case = f.req("case")?.to_owned();
|
|
if !valid_id(&case) {
|
|
return Err(format!("--case {case:?} is not a plain identifier"));
|
|
}
|
|
let slices = f.number::<usize>("slices")?.unwrap_or(20);
|
|
if !(1..=100_000).contains(&slices) {
|
|
return Err("--slices must be 1..100000".to_owned());
|
|
}
|
|
Ok(AltArgs {
|
|
dir: PathBuf::from(f.req("run-dir")?),
|
|
case,
|
|
rounds,
|
|
batch,
|
|
pin: f.number::<usize>("pin")?.ok_or("--pin is required")?,
|
|
schedule: PathBuf::from(f.req("schedule")?),
|
|
seed: f.number::<u64>("seed")?.unwrap_or(1),
|
|
out: f.get("out").map(PathBuf::from),
|
|
slices,
|
|
slice_ms: f.number::<f64>("slice-ms")?,
|
|
llc_bytes: f.number::<u64>("llc-bytes")?,
|
|
machine_role: f.get("machine-role").map(str::to_owned),
|
|
kab: f.get("kab").map(PathBuf::from),
|
|
})
|
|
}
|
|
|
|
fn create_new_file(path: &Path, bytes: &[u8]) -> Result<(), String> {
|
|
let mut f = fs::OpenOptions::new().write(true).create_new(true).open(path).map_err(|e| format!("{}: {e} (nothing is overwritten)", path.display()))?;
|
|
f.write_all(bytes).map_err(|e| format!("{}: {e}", path.display()))
|
|
}
|
|
|
|
fn file_sha(path: &Path) -> Result<String, String> {
|
|
fs::read(path).map(|b| sha_hex(&b)).map_err(|e| format!("{}: {e}", path.display()))
|
|
}
|
|
|
|
fn ours_flags() -> String {
|
|
format!("cargo profile {}; RUSTFLAGS={:?}; target-cpu default", if cfg!(debug_assertions) { "dev" } else { "release" }, std::env::var("RUSTFLAGS").unwrap_or_default())
|
|
}
|
|
|
|
fn cmd_alternate(args: &[String]) -> Result<ExitCode, String> {
|
|
let a = parse_alt_args(args)?;
|
|
let started = now_utc();
|
|
let verified = match verify_dir(&a.dir) {
|
|
Ok(v) => v,
|
|
Err(e) => {
|
|
println!("{e}");
|
|
return Ok(ExitCode::from(if e.incomplete { 2 } else { 1 }));
|
|
}
|
|
};
|
|
let case = verified.cases.iter().find(|c| c.id == a.case).ok_or_else(|| format!("case {} is not in the manifest", a.case))?.clone();
|
|
let out = a.out.clone().unwrap_or_else(|| {
|
|
let name = a.dir.file_name().map_or_else(|| "kab1".to_owned(), |n| n.to_string_lossy().into_owned());
|
|
a.dir.parent().unwrap_or(Path::new(".")).join(format!("{name}.alt-{}", a.case))
|
|
});
|
|
let abs = |p: &Path| std::path::absolute(p).unwrap_or_else(|_| p.to_path_buf());
|
|
if abs(&out).starts_with(abs(&a.dir)) || abs(&a.dir).starts_with(abs(&out)) {
|
|
return Err("--out must not contain or lie inside the KAB1 directory".to_owned());
|
|
}
|
|
if inside_git_checkout(&out) || inside_git_checkout(&a.schedule) {
|
|
return Err("--out and --schedule must lie outside every Git checkout (generated artifacts stay out of Git)".to_owned());
|
|
}
|
|
let own_exe = std::env::current_exe().map_err(|e| format!("current_exe: {e}"))?;
|
|
let kab = a.kab.clone().or_else(|| std::env::var_os("KAB").map(PathBuf::from)).unwrap_or_else(|| {
|
|
PathBuf::from(std::env::var("E2E_ROOT").unwrap_or_else(|_| format!("{}/work/leleka-e2e", std::env::var("HOME").unwrap_or_default()))).join("build/kernel-ab/kab")
|
|
});
|
|
if !kab.is_file() {
|
|
return Err(format!("the C++ driver {} does not exist (build tools/kernel-ab/cpp, or pass --kab / set KAB)", kab.display()));
|
|
}
|
|
// a host without AVX-512 has no avx512 cells (the C++ reference trees are identical by construction there)
|
|
let trees: Vec<&'static str> = TREES.iter().copied().filter(|t| *t != "avx512" || verified.provenance.avx512_ok != Some(false)).collect();
|
|
let procs = procs_for(&trees);
|
|
|
|
// the schedule, written BEFORE the first run and read back: the file, not the generator, drives the batch
|
|
let first_round = (a.batch - 1) * a.rounds + 1;
|
|
let planned = make_schedule(a.seed, a.batch, a.rounds, &procs);
|
|
let text = schedule_text(a.seed, a.batch, a.rounds, &a.case, a.pin, first_round, &planned);
|
|
fs::create_dir_all(&out).map_err(|e| format!("{}: {e}", out.display()))?;
|
|
if let Some(parent) = a.schedule.parent().filter(|p| !p.as_os_str().is_empty()) {
|
|
fs::create_dir_all(parent).map_err(|e| format!("{}: {e}", parent.display()))?;
|
|
}
|
|
create_new_file(&a.schedule, text.as_bytes())?;
|
|
let schedule = parse_schedule(&fs::read_to_string(&a.schedule).map_err(|e| format!("{}: {e}", a.schedule.display()))?)?;
|
|
println!("schedule written to {} (sha256 {}) before the first run: {} rounds x {} processes", a.schedule.display(), sha_hex(text.as_bytes()), schedule.len(), procs.len());
|
|
let (records_dir, proc_dir) = (out.join("records"), out.join("processes"));
|
|
for d in [&records_dir, &proc_dir] {
|
|
fs::create_dir_all(d).map_err(|e| format!("{}: {e}", d.display()))?;
|
|
}
|
|
let parent_env: Vec<(OsString, OsString)> = std::env::vars_os().collect();
|
|
let sibling_at_start = sibling_idle(a.pin);
|
|
let machine_role = a.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();
|
|
|
|
// equality phase: our tree against the C++ reference .out file, per tree, in fresh processes (the kernels are not touched by timing)
|
|
let eq_dir = out.join(format!("equality-b{:04}", a.batch));
|
|
let mut equality: BTreeMap<&'static str, Outcome> = BTreeMap::new();
|
|
for tree in &trees {
|
|
let p = Proc { imp: Impl::Rust, tree, rep: 'a' };
|
|
let mut cmd = scrubbed_command(&own_exe, &parent_env, &cell_env(&p));
|
|
cmd.arg("run-tree").arg(&a.dir).args(["--tree", tree, "--case", &a.case, "--out"]).arg(&eq_dir).args(["--pin", &a.pin.to_string()]);
|
|
run_cell(&mut cmd, &format!("{}/equality", p.name()))?;
|
|
let ours_name = format!("case-{}.rust-{tree}.out", a.case);
|
|
let ours = read_out(&eq_dir.join(&ours_name), &ours_name, case.rows, tree, None).map_err(|e| e.to_string())?;
|
|
let o = case.outs.iter().find(|o| o.tree == *tree).ok_or("missing reference out")?;
|
|
let reference = read_out(&a.dir.join(&o.name), &o.name, case.rows, tree, Some((&o.sha256, o.bytes))).map_err(|e| e.to_string())?;
|
|
let outcome = compare_bits(&ours, &reference, case.tolerance.as_ref());
|
|
println!(
|
|
"EQUALITY {} [{tree}] {}{}",
|
|
a.case,
|
|
if outcome.equal() { "EQUAL" } else { "NOT_EQUAL" },
|
|
outcome.first_mismatch.map_or(format!("; {} values", outcome.compared), |(i, x, y)| format!("; {} of {} values differ, first at {i}: ours {x:#010x} reference {y:#010x}, max abs error {:e}", outcome.mismatches, outcome.compared, outcome.max_abs_error))
|
|
);
|
|
equality.insert(tree, outcome);
|
|
}
|
|
|
|
let mut cpu_model = String::new();
|
|
let batch_json = |cpu_model: String, equality: &BTreeMap<&'static str, Outcome>| -> Result<String, String> {
|
|
let eq = equality
|
|
.iter()
|
|
.map(|(t, o)| {
|
|
format!(
|
|
"{{\"tree\": {}, \"verdict\": \"{}\", \"mode\": \"{}\", \"compared_values\": {}, \"mismatches\": {}}}",
|
|
jstr(t),
|
|
if o.equal() { "EQUAL" } else { "NOT_EQUAL" },
|
|
if case.tolerance.is_some() { "tolerance" } else { "bitwise" },
|
|
o.compared,
|
|
o.mismatches
|
|
)
|
|
})
|
|
.collect::<Vec<_>>()
|
|
.join(", ");
|
|
let cells = procs
|
|
.iter()
|
|
.map(|p| format!("{{\"process\": {}, \"impl\": {}, \"tree\": {}, \"env_set\": {}, \"env_scrubbed\": \"every STRATA_* and LELEKA_* variable of the parent\"}}", jstr(&p.name()), jstr(p.imp.name()), jstr(p.tree), json_env(&cell_env(p).into_iter().collect())))
|
|
.collect::<Vec<_>>()
|
|
.join(", ");
|
|
Ok(format!(
|
|
"{{\n \"format\": \"KAB1-alt\",\n \"version\": 1,\n \"batch\": {},\n \"rounds\": {},\n \"first_round\": {first_round},\n \"run_started_utc\": {},\n \"case\": {},\n \"run_dir\": {},\n \"manifest_sha256\": {},\n \"input_sha256\": {},\n \"pin\": {{\"logical_cpu\": {}, \"sibling_idle_at_start\": {sibling_at_start}}},\n \"pool\": {{\"workers\": 1}},\n \"machine\": {{\"machine_role\": {}, \"cpu_model\": {}, \"os\": {}}},\n \"seed\": {},\n \"schedule\": {{\"file\": {}, \"sha256\": {}}},\n \"kab\": {{\"path\": {}, \"sha256\": {}}},\n \"rust_example\": {{\"path\": {}, \"sha256\": {}}},\n \"slices_per_regime\": {},\n \"slice_ms\": {},\n \"equality\": [{eq}],\n \"cells\": [{cells}],\n \"no_statistics\": \"this file computes no class, no interval and no A/A verdict (S0.10b, STRA-313)\"\n}}\n",
|
|
a.batch,
|
|
a.rounds,
|
|
jstr(&started),
|
|
jstr(&a.case),
|
|
jstr(&a.dir.display().to_string()),
|
|
jstr(&verified.manifest_sha256),
|
|
jstr(&case.in_sha256),
|
|
a.pin,
|
|
jstr(&machine_role),
|
|
jstr(&cpu_model),
|
|
jstr(&host_os()),
|
|
a.seed,
|
|
jstr(&a.schedule.display().to_string()),
|
|
jstr(&sha_hex(text.as_bytes())),
|
|
jstr(&kab.display().to_string()),
|
|
jstr(&file_sha(&kab)?),
|
|
jstr(&own_exe.display().to_string()),
|
|
jstr(&file_sha(&own_exe)?),
|
|
a.slices,
|
|
a.slice_ms.map_or("null".to_owned(), |m| jnum(m, 1))
|
|
))
|
|
};
|
|
|
|
let expect = Expect { manifest_sha: &verified.manifest_sha256, input_sha: &case.in_sha256, case: &a.case, pin: a.pin };
|
|
let mut ctx = BatchCtx {
|
|
verified: &verified,
|
|
case: &case,
|
|
pin: a.pin,
|
|
machine_role: machine_role.clone(),
|
|
os: host_os(),
|
|
cpu_model: String::new(),
|
|
started_utc: started.clone(),
|
|
rust_tool: Tool { compiler: "rustc".to_owned(), version: rustc_version, triple, flags: ours_flags() },
|
|
batch: a.batch,
|
|
equality: &equality,
|
|
};
|
|
let mut written = Vec::new();
|
|
for (round_no, order) in &schedule {
|
|
let mut done: Vec<ProcOut> = Vec::new();
|
|
for p in order {
|
|
let name = p.name();
|
|
let file = proc_dir.join(format!("r{round_no:05}-{name}.json"));
|
|
let mut cmd = scrubbed_command(if p.imp == Impl::Cpp { &kab } else { &own_exe }, &parent_env, &cell_env(p));
|
|
cmd.arg("time").args(["--run-dir"]).arg(&a.dir).args(["--case", &a.case, "--slices", &a.slices.to_string(), "--pin", &a.pin.to_string(), "--out"]).arg(&file);
|
|
if let Some(ms) = a.slice_ms {
|
|
cmd.args(["--slice-ms", &ms.to_string()]);
|
|
}
|
|
if let Some(b) = a.llc_bytes {
|
|
cmd.args(["--llc-bytes", &b.to_string()]);
|
|
}
|
|
let res = run_cell(&mut cmd, &name)?;
|
|
fs::write(file.with_extension("log"), [&res.stdout[..], &res.stderr[..]].concat()).map_err(|e| format!("{}: {e}", file.display()))?;
|
|
let bytes = fs::read(&file).map_err(|e| format!("cell {name}: its output {} was not written: {e}", file.display()))?;
|
|
done.push(parse_proc_json(p, &bytes, &expect)?);
|
|
}
|
|
if cpu_model.is_empty() {
|
|
cpu_model = done.iter().find_map(|d| d.cpu_model.clone()).unwrap_or_else(|| "unknown model".to_owned());
|
|
ctx.cpu_model = cpu_model.clone();
|
|
create_new_file(&out.join(format!("batch-{:04}.json", a.batch)), batch_json(cpu_model.clone(), &equality)?.as_bytes())?;
|
|
}
|
|
for (name, json) in round_records(&ctx, *round_no, &done)? {
|
|
create_new_file(&records_dir.join(&name), json.as_bytes())?;
|
|
written.push(name);
|
|
}
|
|
println!("round {round_no} done: {}", order.iter().map(Proc::name).collect::<Vec<_>>().join(" "));
|
|
}
|
|
println!("ALTERNATE OK batch={} rounds={} records={} dir={}", a.batch, a.rounds, written.len(), records_dir.display());
|
|
for (t, o) in &equality {
|
|
println!("EQUALITY-SUMMARY {} {t} {}", a.case, if o.equal() { "EQUAL" } else { "NOT_EQUAL" });
|
|
}
|
|
Ok(ExitCode::SUCCESS)
|
|
}
|
|
|
|
// ------------------------------------------------------------------------------------------------ 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] [--case ID]");
|
|
eprintln!(" kernel_ab time --run-dir D --case ID --slices N --pin CPU --out F.json [--slice-ms 60] [--regime both|resident|streamed] [--llc-bytes B]");
|
|
eprintln!(" kernel_ab alternate --run-dir D --case ID --rounds N --batch K --pin CPU --schedule FILE [--seed S] [--out R] [--slices N] [--slice-ms MS] [--llc-bytes B] [--machine-role NAME] [--kab PATH]");
|
|
ExitCode::from(64)
|
|
}
|
|
|
|
fn main() -> ExitCode {
|
|
let args: Vec<String> = std::env::args().skip(1).collect();
|
|
// `time` and `alternate` take flags only (the command line of `kab time`); the older commands take the directory first
|
|
if let Some(cmd @ ("time" | "alternate")) = args.first().map(String::as_str) {
|
|
let result = if cmd == "time" { cmd_time(&args[1..]) } else { cmd_alternate(&args[1..]) };
|
|
return result.unwrap_or_else(|e| {
|
|
eprintln!("kernel_ab {cmd}: {e}");
|
|
ExitCode::from(1)
|
|
});
|
|
}
|
|
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, opts.case.as_deref()),
|
|
_ => 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);
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------------------------------- alternation (STRA-318)
|
|
|
|
#[test]
|
|
fn the_schedule_is_reproducible_from_the_seed() {
|
|
let procs = procs_for(&TREES);
|
|
let a = make_schedule(7, 1, 30, &procs);
|
|
assert_eq!(a, make_schedule(7, 1, 30, &procs));
|
|
assert_ne!(a, make_schedule(8, 1, 30, &procs), "another seed gives another schedule");
|
|
assert_ne!(a, make_schedule(7, 2, 30, &procs), "another batch gives another schedule");
|
|
assert_eq!(a.len(), 30);
|
|
// the text round-trips through the file format and names the seed
|
|
let text = schedule_text(7, 1, 30, "18-20-r1", 9, 1, &a);
|
|
assert!(text.contains("seed=7 batch=1 rounds=30 case=18-20-r1 pin=9"));
|
|
let back = parse_schedule(&text).unwrap();
|
|
assert_eq!(back.iter().map(|r| r.1.clone()).collect::<Vec<_>>(), a);
|
|
assert_eq!(back[0].0, 1);
|
|
assert_eq!(back[29].0, 30);
|
|
}
|
|
|
|
#[test]
|
|
fn the_rotation_gives_every_process_every_position_within_a_block() {
|
|
let procs = procs_for(&TREES);
|
|
assert_eq!(procs.len(), 8);
|
|
let s = make_schedule(3, 1, 16, &procs);
|
|
for block in s.chunks(8) {
|
|
for round in block {
|
|
let mut names: Vec<_> = round.iter().map(Proc::name).collect();
|
|
names.sort();
|
|
assert_eq!(names.len(), 8);
|
|
names.dedup();
|
|
assert_eq!(names.len(), 8, "every process exactly once per round");
|
|
}
|
|
for pos in 0..8 {
|
|
let at: BTreeSet<_> = block.iter().map(|r| r[pos]).collect();
|
|
assert_eq!(at.len(), 8, "position {pos} is taken by every process once per block of 8 rounds");
|
|
}
|
|
}
|
|
// a host without AVX-512 has only the avx2 cells
|
|
assert_eq!(procs_for(&["avx2"]).len(), 4);
|
|
}
|
|
|
|
#[test]
|
|
fn a_schedule_file_is_written_once_and_a_bad_one_is_refused() {
|
|
let t = TempDir::new();
|
|
let f = t.0.join("schedule.tsv");
|
|
create_new_file(&f, b"x").unwrap();
|
|
assert!(create_new_file(&f, b"y").unwrap_err().contains("nothing is overwritten"));
|
|
assert_eq!(fs::read(&f).unwrap(), b"x");
|
|
let procs = procs_for(&TREES);
|
|
let good = schedule_text(1, 1, 3, "c", 0, 1, &make_schedule(1, 1, 3, &procs));
|
|
assert!(parse_schedule(&good).is_ok());
|
|
assert!(parse_schedule("nope").is_err());
|
|
assert!(parse_schedule(&good.replace("cpp-avx2-a", "cpp-avx2-z")).unwrap_err().contains("unknown process"));
|
|
assert!(parse_schedule(&good.replacen("\n2\t", "\n5\t", 1)).unwrap_err().contains("does not follow"));
|
|
// a round that names one process twice (and so lacks another) is refused
|
|
let dup = good.lines().map(|l| if l.starts_with("2\t") { l.replacen("rust-avx2-b", "rust-avx2-a", 1).replacen("rust-avx2-b", "rust-avx2-a", 1) } else { l.to_owned() }).collect::<Vec<_>>().join("\n");
|
|
assert!(parse_schedule(&dup).is_err());
|
|
}
|
|
|
|
/// The child side of the environment test: prints the managed variables it sees. Does nothing in a normal run.
|
|
#[test]
|
|
fn env_probe_child() {
|
|
if std::env::var_os("KAB_TEST_CHILD").as_deref() != Some(std::ffi::OsStr::new("probe")) {
|
|
return;
|
|
}
|
|
for (k, v) in std::env::vars() {
|
|
if is_managed_name(&k) {
|
|
println!("PROBE {k}={v}");
|
|
}
|
|
}
|
|
}
|
|
|
|
/// The child side of the failure test.
|
|
#[test]
|
|
fn failing_child() {
|
|
if std::env::var_os("KAB_TEST_CHILD").as_deref() == Some(std::ffi::OsStr::new("fail")) {
|
|
eprintln!("simulated kernel failure");
|
|
std::process::exit(3);
|
|
}
|
|
}
|
|
|
|
fn child(test: &str, mode: &str, planted: &[(&str, &str)], cell: &[(String, String)]) -> Command {
|
|
let mut parent: Vec<(OsString, OsString)> = std::env::vars_os().filter(|(k, _)| !is_managed_name(&k.to_string_lossy())).collect();
|
|
parent.push(("KAB_TEST_CHILD".into(), mode.into()));
|
|
parent.extend(planted.iter().map(|(k, v)| ((*k).into(), (*v).into())));
|
|
let mut c = scrubbed_command(&std::env::current_exe().unwrap(), &parent, cell);
|
|
c.args(["--exact", test, "--nocapture", "--test-threads=1"]);
|
|
c
|
|
}
|
|
|
|
#[test]
|
|
fn environment_scrubbing_removes_a_planted_strata_variable_and_keeps_only_the_cell() {
|
|
let cell = cell_env(&Proc { imp: Impl::Rust, tree: "avx2", rep: 'a' });
|
|
assert_eq!(
|
|
cell,
|
|
vec![("LELEKA_CPU_POOL_PIN_HOST".to_owned(), "off".to_owned()), ("STRATA_FORCE_AVX2".to_owned(), "1".to_owned()), ("STRATA_POOL_SPIN_US".to_owned(), "0".to_owned())]
|
|
);
|
|
assert!(cell_env(&Proc { imp: Impl::Cpp, tree: "avx512", rep: 'b' }).is_empty());
|
|
let out = run_cell(&mut child("tests::env_probe_child", "probe", &[("STRATA_X", "planted"), ("LELEKA_Y", "planted"), ("strata_lower", "planted")], &cell), "rust-avx2-a").unwrap();
|
|
let text = String::from_utf8_lossy(&out.stdout);
|
|
// libtest prints "test <name> ... " before the child's own output on the same line
|
|
let mut probes: Vec<&str> = text.lines().flat_map(|l| l.split("PROBE ").skip(1)).collect();
|
|
probes.sort_unstable();
|
|
assert_eq!(probes, vec!["LELEKA_CPU_POOL_PIN_HOST=off", "STRATA_FORCE_AVX2=1", "STRATA_POOL_SPIN_US=0"], "only the cell's variables survive:\n{text}");
|
|
// the cpp avx512 cell sets nothing at all
|
|
let out = run_cell(&mut child("tests::env_probe_child", "probe", &[("STRATA_X", "planted")], &[]), "cpp-avx512-a").unwrap();
|
|
assert!(!String::from_utf8_lossy(&out.stdout).contains("PROBE "));
|
|
}
|
|
|
|
#[test]
|
|
fn a_child_failure_is_reported_with_the_cell_named() {
|
|
let e = run_cell(&mut child("tests::failing_child", "fail", &[], &[]), "cpp-avx2-b").unwrap_err();
|
|
assert!(e.starts_with("cell cpp-avx2-b failed (exit 3)"), "{e}");
|
|
assert!(e.contains("simulated kernel failure"), "{e}");
|
|
let e = run_cell(&mut Command::new("kab-does-not-exist-318"), "rust-avx512-a").unwrap_err();
|
|
assert!(e.starts_with("cell rust-avx512-a: cannot start"), "{e}");
|
|
}
|
|
|
|
#[test]
|
|
fn the_time_command_line_is_the_one_of_kab_time() {
|
|
let v = |a: &[&str]| a.iter().map(|s| (*s).to_owned()).collect::<Vec<_>>();
|
|
let t = parse_time_args(&v(&["--run-dir", "D", "--case", "18-20-r1", "--slices", "50", "--pin", "9", "--out", "t.json"])).unwrap();
|
|
assert_eq!((t.slices, t.pin, t.slice_ms, t.regime, t.llc_bytes), (50, 9, 60.0, RegimeSel::Both, None));
|
|
let t = parse_time_args(&v(&["--run-dir", "D", "--case", "c", "--slices", "2", "--pin", "0", "--out", "o", "--slice-ms", "5", "--regime", "streamed", "--llc-bytes", "1000"])).unwrap();
|
|
assert_eq!((t.slice_ms, t.regime, t.llc_bytes), (5.0, RegimeSel::Streamed, Some(1000)));
|
|
for bad in [
|
|
v(&["--run-dir", "D", "--case", "c", "--slices", "0", "--pin", "0", "--out", "o"]),
|
|
v(&["--run-dir", "D", "--case", "c", "--slices", "1", "--out", "o"]),
|
|
v(&["--run-dir", "D", "--case", "c", "--slices", "1", "--pin", "0", "--out", "o", "--regime", "both2"]),
|
|
v(&["--run-dir", "D", "--case", "../c", "--slices", "1", "--pin", "0", "--out", "o"]),
|
|
v(&["--run-dir", "D", "--case", "c", "--slices", "1", "--pin", "0", "--out", "o", "--bogus", "1"]),
|
|
v(&["--run-dir", "D", "--run-dir", "E", "--case", "c", "--slices", "1", "--pin", "0", "--out", "o"]),
|
|
] {
|
|
assert!(parse_time_args(&bad).is_err(), "{bad:?}");
|
|
}
|
|
let a = parse_alt_args(&v(&["--run-dir", "D", "--case", "c", "--rounds", "30", "--batch", "1", "--pin", "9", "--schedule", "s.tsv"])).unwrap();
|
|
assert_eq!((a.rounds, a.batch, a.seed, a.slices), (30, 1, 1, 20));
|
|
assert!(parse_alt_args(&v(&["--run-dir", "D", "--case", "c", "--rounds", "30", "--batch", "0", "--pin", "9", "--schedule", "s"])).is_err());
|
|
}
|
|
|
|
#[test]
|
|
fn medians_percentiles_and_parsers_agree_with_the_reference_rules() {
|
|
assert_eq!(median_of(&[3.0, 1.0, 2.0, 10.0]), 3.0, "sorted, element size/2 as the C++ reference");
|
|
assert_eq!(median_of(&[]), 0.0);
|
|
let v: Vec<f64> = (1..=21).map(f64::from).collect();
|
|
assert_eq!((percentile_of(&v, 0.05), percentile_of(&v, 0.95)), (2.0, 20.0));
|
|
assert_eq!(parse_cpu_list("2,18"), vec![2, 18]);
|
|
assert_eq!(parse_cpu_list("0-3,8"), vec![0, 1, 2, 3, 8]);
|
|
assert_eq!((parse_size("32768K"), parse_size("32M"), parse_size("512")), (32 << 20, 32 << 20, 512));
|
|
assert_eq!(busy_fraction(Some((10, 100)), Some((30, 200))), Some(0.2));
|
|
assert_eq!(busy_fraction(None, Some((1, 1))), None);
|
|
// the calibrated clock of any x86-64 core is in this range (the chain must not be folded away: 175 GHz was the folded multiply chain)
|
|
let ghz = core_ghz();
|
|
assert!((0.3..12.0).contains(&ghz), "{ghz}");
|
|
}
|
|
|
|
#[test]
|
|
fn an_output_inside_a_git_checkout_is_detected() {
|
|
let t = TempDir::new();
|
|
let inner = t.0.join("a/b");
|
|
fs::create_dir_all(&inner).unwrap();
|
|
assert!(!inside_git_checkout(&inner));
|
|
fs::create_dir_all(t.0.join(".git")).unwrap();
|
|
assert!(inside_git_checkout(&inner));
|
|
assert!(inside_git_checkout(&t.0.join("not/yet/created/schedule.tsv")));
|
|
}
|
|
|
|
fn json_regime(label: &str, k: usize, self_key: &str) -> String {
|
|
let slice = |g1: f64| format!("{{\"i\": 0, \"calls\": 10, \"wall_ns\": 100, \"ns_per_call\": 10.0, \"ghz_before\": 5.0, \"ghz_after\": {g1}, \"cycles_per_call\": 50.0}}");
|
|
format!(
|
|
"{{\"regime\": \"{label}\", \"copies_k\": {k}, \"expert_bytes\": 1000, \"llc_bytes\": 500, \"slices_requested\": 3, \"slices_kept\": 2, \"dropped_count\": 1, \"{self_key}\": true, \"median_ns_per_call\": 10.0, \"median_cycles_per_call\": 50.0, \"slices\": [{}, {}], \"dropped\": [{}]}}",
|
|
slice(5.0),
|
|
slice(5.1),
|
|
slice(4.0)
|
|
)
|
|
}
|
|
|
|
/// A process JSON as the C++ writer (`imp` cpp) or this example (rust) writes it, with `env` as its effective environment.
|
|
fn proc_fixture(p: &Proc, env: &str) -> String {
|
|
let (self_key, detail) = if p.imp == Impl::Cpp {
|
|
("selfcheck_bitwise_equal_compose_expert", "{\"tree\": \"avx512\", \"avx2_ok\": true, \"avx512_ok\": true, \"iq512_gather_on\": false, \"iq256_gather_setting\": -1, \"strata_env\": {}}".to_owned())
|
|
} else {
|
|
("selfcheck_bitwise_equal_first_call", format!("{{\"tree\": \"{}\", \"cpu_report\": [\"cpu: logical 16 (8 physical): Test CPU; x\", \"cpu: process kernel family AVX-512 (test)\"], \"strata_env\": {{}}}}", p.tree))
|
|
};
|
|
format!(
|
|
"{{\"format\": \"KAB1-time\", \"version\": 1, \"writer\": \"{}\", \"manifest_sha256\": \"m\", \"case\": {{\"id\": \"c\", \"input_sha256\": \"i\"}}, \"tree\": \"{}\", \"tree_detail\": {detail}, \"effective_env\": {env}, \"pin\": {{\"cpu\": 9, \"sibling_cpu\": 25, \"sibling_busy_fraction_during_run\": 0.01}}, \"clock_calibration\": {{\"ghz_at_start\": 5.0, \"ghz_at_end\": 5.1}}, \"final_output_unchanged\": true, \"output_sha256\": \"{}\", \"regimes\": [{}, {}]}}",
|
|
p.imp.name(),
|
|
p.tree,
|
|
"cd".repeat(32),
|
|
json_regime("RESIDENT", 1, self_key),
|
|
json_regime("STREAMED", 3, self_key)
|
|
)
|
|
}
|
|
|
|
#[test]
|
|
fn a_process_json_is_checked_against_the_cell_that_was_started() {
|
|
let expect = Expect { manifest_sha: "m", input_sha: "i", case: "c", pin: 9 };
|
|
for p in [Proc { imp: Impl::Cpp, tree: "avx2", rep: 'a' }, Proc { imp: Impl::Rust, tree: "avx512", rep: 'b' }] {
|
|
let env = json_env(&cell_env(&p).into_iter().collect());
|
|
let ok = parse_proc_json(&p, proc_fixture(&p, &env).as_bytes(), &expect).unwrap();
|
|
assert_eq!(ok.regimes.len(), 2);
|
|
let r = &ok.regimes["STREAMED"];
|
|
assert_eq!((r.copies_k, r.ns.len(), r.dropped, r.requested), (3, 2, 1, 3));
|
|
assert!((r.max_drift - 0.2).abs() < 1e-9, "the dropped slice's 20 percent drift is the maximum: {}", r.max_drift);
|
|
assert_eq!(ok.sibling_idle, Some(true));
|
|
// the environment the process saw must be exactly the cell's
|
|
let planted = json_env(&BTreeMap::from([("STRATA_X".to_owned(), "1".to_owned())]));
|
|
let e = parse_proc_json(&p, proc_fixture(&p, &planted).as_bytes(), &expect).unwrap_err();
|
|
assert!(e.starts_with(&format!("cell {}: effective environment", p.name())), "{e}");
|
|
// wrong pin, wrong manifest, wrong input, wrong writer: each names the cell
|
|
for (bad_expect, what) in [
|
|
(Expect { manifest_sha: "m", input_sha: "i", case: "c", pin: 8 }, "pinned to CPU"),
|
|
(Expect { manifest_sha: "other", input_sha: "i", case: "c", pin: 9 }, "manifest_sha256"),
|
|
(Expect { manifest_sha: "m", input_sha: "x", case: "c", pin: 9 }, "input hash"),
|
|
] {
|
|
let e = parse_proc_json(&p, proc_fixture(&p, &env).as_bytes(), &bad_expect).unwrap_err();
|
|
assert!(e.starts_with(&format!("cell {}:", p.name())) && e.contains(what), "{e}");
|
|
}
|
|
let other = Proc { imp: if p.imp == Impl::Cpp { Impl::Rust } else { Impl::Cpp }, ..p };
|
|
assert!(parse_proc_json(&other, proc_fixture(&p, &env).as_bytes(), &expect).unwrap_err().contains("writer"));
|
|
}
|
|
}
|
|
|
|
fn fake_proc(p: Proc, base: f64) -> ProcOut {
|
|
let regime = |k: usize| RegimeStat {
|
|
copies_k: k,
|
|
expert_bytes: 1_000_000,
|
|
llc_bytes: 1_000,
|
|
requested: 10,
|
|
dropped: 1,
|
|
median_ns: base,
|
|
median_cycles: base * 5.0,
|
|
ns: vec![base * 0.9, base, base * 1.1],
|
|
cycles: vec![base * 4.5, base * 5.0, base * 5.5],
|
|
max_drift: 0.01,
|
|
selfcheck: true,
|
|
};
|
|
ProcOut {
|
|
proc: p,
|
|
regimes: BTreeMap::from([("RESIDENT".to_owned(), regime(1)), ("STREAMED".to_owned(), regime(3))]),
|
|
ghz_start: 5.0,
|
|
ghz_end: 5.1,
|
|
sibling_idle: Some(true),
|
|
final_unchanged: true,
|
|
output_sha: Some("ab".repeat(32)),
|
|
tree_text: format!("tree text of {}", p.name()),
|
|
cpu_model: Some("Test CPU".to_owned()),
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn round_records_have_the_schema_shape_and_keep_not_equal() {
|
|
let t = TempDir::new();
|
|
build(&t.0, &one_case(), |_| {});
|
|
let v = verify_dir(&t.0).unwrap();
|
|
let outcome = |bad: usize| Outcome { compared: H, mismatches: bad, differing_bits: bad, max_abs_error: 0.0, first_mismatch: None };
|
|
let equality = BTreeMap::from([("avx512", outcome(0)), ("avx2", outcome(1835))]);
|
|
let ctx = BatchCtx {
|
|
verified: &v,
|
|
case: &v.cases[0],
|
|
pin: 9,
|
|
machine_role: "m".into(),
|
|
os: "os".into(),
|
|
cpu_model: "cpu".into(),
|
|
started_utc: "2026-10-28T20:00:00Z".into(),
|
|
rust_tool: Tool { compiler: "rustc".into(), version: "rustc 1.99.0".into(), triple: "x86_64-unknown-linux-gnu".into(), flags: "f".into() },
|
|
batch: 2,
|
|
equality: &equality,
|
|
};
|
|
let mut done: Vec<ProcOut> = procs_for(&TREES).into_iter().enumerate().map(|(i, p)| fake_proc(p, 100.0 + i as f64)).collect();
|
|
done.reverse(); // the order of execution does not matter to the records
|
|
done.iter_mut().find(|p| p.proc == Proc { imp: Impl::Cpp, tree: "avx2", rep: 'b' }).unwrap().sibling_idle = Some(false);
|
|
let files = round_records(&ctx, 31, &done).unwrap();
|
|
assert_eq!(files.len(), 12, "2 trees x 2 regimes x (A/B + A/A cpp + A/A rust)");
|
|
let names: BTreeSet<_> = files.iter().map(|f| f.0.as_str()).collect();
|
|
assert_eq!(names.len(), 12);
|
|
assert!(names.contains("r00031.ab.avx2.streamed.json") && names.contains("r00031.aa-cpp.avx512.resident.json") && names.contains("r00031.aa-rust.avx2.resident.json"));
|
|
for (name, json) in &files {
|
|
let rec = parse_json(json.as_bytes()).unwrap_or_else(|e| panic!("{name}: {e}"));
|
|
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(), "{name}: {key}");
|
|
}
|
|
assert_eq!(rec.str("level").unwrap(), "COMPONENT_KERNEL");
|
|
assert_eq!(rec.str("kab1_manifest_sha256").unwrap(), v.manifest_sha256);
|
|
assert_eq!(rec.str("input_sha256").unwrap(), v.cases[0].in_sha256);
|
|
let Some(Json::Arr(rows)) = rec.get("rows") else { panic!("rows") };
|
|
let units: Vec<_> = rows.iter().map(|r| r.str("unit").unwrap().to_owned()).collect();
|
|
assert_eq!(units, ["ns", "cycles"]);
|
|
assert_ne!(rows[0].str("row_type").unwrap(), rows[1].str("row_type").unwrap(), "no repeated row type");
|
|
let regime = rec.str("regime").unwrap();
|
|
assert_eq!(rec.get("streamed").is_some(), regime == "streamed", "{name}");
|
|
assert!(rec.str("kernel").unwrap().contains("PLACEHOLDER"));
|
|
let eq = rec.req("equality").unwrap();
|
|
let tree = rec.req("tree").unwrap().str("ours").unwrap();
|
|
let want = if name.contains(".ab.") && tree == "avx2" { "NOT_EQUAL" } else { "EQUAL" };
|
|
assert_eq!(eq.str("verdict").unwrap(), want, "{name}");
|
|
if want == "NOT_EQUAL" {
|
|
assert_eq!(eq.uint("mismatches").unwrap(), 1835, "the A/B mismatch count is carried, not hidden");
|
|
}
|
|
}
|
|
// the A/B record puts Rust in the ours slot and C++ in the reference slot; the A/A records use one implementation on both
|
|
let ab = parse_json(files.iter().find(|f| f.0 == "r00031.ab.avx512.resident.json").unwrap().1.as_bytes()).unwrap();
|
|
assert!(ab.str("kernel").unwrap().contains("ours-slot process rust-avx512-a, reference-slot process cpp-avx512-a"));
|
|
assert_eq!(ab.req("toolchain").unwrap().req("ours").unwrap().str("compiler").unwrap(), "rustc");
|
|
let aa = parse_json(files.iter().find(|f| f.0 == "r00031.aa-cpp.avx512.resident.json").unwrap().1.as_bytes()).unwrap();
|
|
assert!(aa.str("kernel").unwrap().contains("ours-slot process cpp-avx512-a, reference-slot process cpp-avx512-b"));
|
|
assert_eq!(aa.req("equality").unwrap().str("mode").unwrap(), "bitwise");
|
|
// sibling_idle belongs to the two processes of a record: only the A/A cpp avx2 records see the busy sibling of cpp-avx2-b
|
|
for (name, json) in &files {
|
|
let rec = parse_json(json.as_bytes()).unwrap();
|
|
let busy = name.contains(".aa-cpp.avx2.");
|
|
assert_eq!(matches!(rec.req("pin").unwrap().get("sibling_idle"), Some(Json::Bool(false))), busy, "{name}");
|
|
}
|
|
// a streamed set that differs between the two sides of a record is refused
|
|
let mut skewed = done.clone();
|
|
skewed.iter_mut().find(|p| p.proc == Proc { imp: Impl::Cpp, tree: "avx2", rep: 'a' }).unwrap().regimes.get_mut("STREAMED").unwrap().copies_k = 4;
|
|
assert!(round_records(&ctx, 31, &skewed).unwrap_err().contains("streamed set differs"));
|
|
// a missing process is named
|
|
assert!(round_records(&ctx, 31, &done[1..]).unwrap_err().contains("did not run"));
|
|
}
|
|
|
|
#[test]
|
|
fn the_rust_time_mode_writes_a_process_json_the_runner_accepts() {
|
|
let t = TempDir::new();
|
|
build(&t.0, &one_case(), |_| {});
|
|
let out = TempDir::new();
|
|
let file = out.0.join("t.json");
|
|
let args: Vec<String> = ["--run-dir", t.0.to_str().unwrap(), "--case", "42-42-r1", "--slices", "40", "--pin", "0", "--out", file.to_str().unwrap(), "--slice-ms", "1", "--llc-bytes", "8000000"].iter().map(|s| (*s).to_owned()).collect();
|
|
// exit 0, or 3 when a 1 ms slice of a ramping clock was dropped in every slice of a regime (kept slices are the loaded host's call)
|
|
let code = format!("{:?}", cmd_time(&args).unwrap());
|
|
assert!(code == format!("{:?}", ExitCode::SUCCESS) || code == format!("{:?}", ExitCode::from(3)), "{code}");
|
|
let text = fs::read_to_string(&file).unwrap();
|
|
let j = parse_json(text.as_bytes()).unwrap();
|
|
assert_eq!(j.str("writer").unwrap(), "rust");
|
|
assert_eq!(j.str("format").unwrap(), "KAB1-time");
|
|
assert!(j.flag("selfcheck_bitwise_equal_first_call").unwrap());
|
|
assert_eq!(j.str("output_sha256").unwrap().len(), 64);
|
|
let tree = j.str("tree").unwrap().to_owned();
|
|
let p = Proc { imp: Impl::Rust, tree: TREES.iter().find(|t| **t == tree).copied().unwrap(), rep: 'a' };
|
|
if !code.contains("(0)") {
|
|
return;
|
|
}
|
|
let manifest = fs::read(t.0.join("manifest.json")).unwrap();
|
|
let (_, _, cases, _) = read_manifest(&t.0).unwrap();
|
|
let sha = sha_hex(&manifest);
|
|
let expect = Expect { manifest_sha: &sha, input_sha: &cases[0].in_sha256, case: "42-42-r1", pin: 0 };
|
|
// the test process runs unscrubbed (its effective environment is empty), so the runner's environment check refuses it ...
|
|
assert!(parse_proc_json(&p, text.as_bytes(), &expect).unwrap_err().contains("effective environment"));
|
|
// ... and accepts it once the recorded environment is the cell's
|
|
let want_env = json_env(&cell_env(&p).into_iter().collect());
|
|
let as_cell = text.replacen("\"effective_env\": {}", &format!("\"effective_env\": {want_env}"), 1);
|
|
let ok = parse_proc_json(&p, as_cell.as_bytes(), &expect).unwrap();
|
|
for r in ["RESIDENT", "STREAMED"] {
|
|
let s = &ok.regimes[r];
|
|
assert!(s.median_ns > 0.0 && s.median_cycles > 0.0 && !s.ns.is_empty(), "{r}");
|
|
assert_eq!(s.requested, 40);
|
|
}
|
|
assert_eq!(ok.regimes["RESIDENT"].copies_k, 1);
|
|
assert!(ok.regimes["STREAMED"].copies_k >= 2);
|
|
assert!(ok.tree_text.starts_with("leleka-serve cpu: process kernel family"));
|
|
// a lie about the pin is refused
|
|
assert!(parse_proc_json(&p, as_cell.as_bytes(), &Expect { pin: 3, ..expect }).unwrap_err().contains("pinned to CPU"));
|
|
}
|
|
|
|
#[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()));
|
|
}
|
|
}
|