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

242 lines
10 KiB
Rust

//! Moved out of the parent module by STRA-338: fn cmd_compare, impl Flags, fn mono_ns, fn core_ghz, fn median_of, fn percentile_of ....
#[allow(unused_imports)]
use super::*;
pub(super) 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) })
}
impl Flags {
pub(super) 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))
}
pub(super) fn get(&self, k: &str) -> Option<&str> {
self.0.iter().find(|(n, _)| n == k).map(|(_, v)| v.as_str())
}
pub(super) fn req(&self, k: &str) -> Result<&str, String> {
self.get(k).ok_or_else(|| format!("--{k} is required"))
}
pub(super) 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()
}
}
pub(super) 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.
pub(super) 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
}
pub(super) 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).
pub(super) 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]
}
pub(super) fn jnum(v: f64, decimals: usize) -> String {
if v.is_finite() { format!("{v:.decimals$}") } else { "null".to_owned() }
}
pub(super) fn read_text(path: &str) -> String {
fs::read_to_string(path).map(|s| s.trim().to_owned()).unwrap_or_default()
}
pub(super) 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
}
pub(super) 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,
}
}