git mv of the files and of the module directories next to them, mod declarations, #[path] attributes and the paths that name the modules, rewritten by scripts/dev/rename_mechanical.py from a reviewed name table. Two files lost one to two lines so the 400-line limit holds again (qsa_prompt_index, original_verify_expert_probe). limits-baseline.json: test fn_lines 0 -> 1 is --allow-increase for crates/deploy builtin_profiles.rs:149 (37 lines, the speed-vs-strata session's file, not touched here); the prod params census falls 108 -> 1 (w_launch, extern C ABI). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
353 lines
14 KiB
Rust
353 lines
14 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::*;
|
|
|
|
/// The result of `compare` for one tree.
|
|
enum TreeOutcome {
|
|
/// The tree was not run: this host has no AVX-512.
|
|
Skipped,
|
|
/// The Rust process failed; `compare` stops with exit 1.
|
|
Failed,
|
|
Compared {
|
|
cells: usize,
|
|
all_equal: bool,
|
|
},
|
|
}
|
|
|
|
/// What one tree's comparison needs besides the run: the tree, its process report and the sibling state.
|
|
struct TreeCtx<'a> {
|
|
tree: &'a str,
|
|
tree_name: &'static str,
|
|
report: &'a [String],
|
|
sibling: bool,
|
|
}
|
|
|
|
/// What `compare` knows about the run directory and the host, fixed for every tree and case.
|
|
struct CompareRun<'a> {
|
|
dir: &'a Path,
|
|
opts: &'a Options,
|
|
verified: &'a Verified,
|
|
out: PathBuf,
|
|
records: PathBuf,
|
|
exe: PathBuf,
|
|
parent_env: Vec<(OsString, OsString)>,
|
|
machine_role: String,
|
|
tool: Tool,
|
|
started: String,
|
|
}
|
|
|
|
/// The tree as the `'static` name the cell environment uses (an unknown tree runs as avx2).
|
|
fn static_tree(tree: &str) -> &'static str {
|
|
TREES.iter().find(|t| **t == tree).copied().unwrap_or("avx2")
|
|
}
|
|
|
|
/// The output directory: `--out`, else beside the run directory; it must be disjoint from it and empty.
|
|
fn compare_out_dir(dir: &Path, opts: &Options) -> Result<PathBuf, String> {
|
|
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()));
|
|
}
|
|
Ok(out)
|
|
}
|
|
|
|
/// "bitwise EQUAL" / "bitwise NOT EQUAL", or the verdict with the tolerance and its basis.
|
|
fn case_label(c: &CaseEntry, outcome: &Outcome) -> String {
|
|
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
|
|
),
|
|
}
|
|
}
|
|
|
|
/// The first mismatch of an outcome, or the number of compared values.
|
|
pub(super) fn mismatch_detail(outcome: &Outcome) -> String {
|
|
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),
|
|
}
|
|
}
|
|
|
|
impl<'a> CompareRun<'a> {
|
|
fn new(dir: &'a Path, opts: &'a Options, verified: &'a Verified, started: String) -> Result<Self, String> {
|
|
let out = compare_out_dir(dir, opts)?;
|
|
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 (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 tool = Tool { compiler: "rustc".to_owned(), version, triple, flags };
|
|
Ok(Self { dir, opts, verified, out, records, exe, parent_env, machine_role, tool, started })
|
|
}
|
|
|
|
/// Runs `run-tree` for one tree in a fresh process and returns its output.
|
|
fn run_tree_process(&self, tree: &str) -> Result<std::process::Output, String> {
|
|
let probe = Proc { imp: Impl::Rust, tree: static_tree(tree), rep: 'a' };
|
|
let mut cmd = scrubbed_command(&self.exe, &self.parent_env, &cell_env(&probe));
|
|
cmd.arg("run-tree")
|
|
.arg(self.dir)
|
|
.args(["--tree", tree, "--out"])
|
|
.arg(&self.out)
|
|
.args(["--pin", &self.opts.pin.to_string()]);
|
|
cmd.output().map_err(|e| format!("cannot start the {tree} process: {e}"))
|
|
}
|
|
|
|
/// Every requested tree; None when a Rust process failed. Otherwise (all equal, compared cells).
|
|
fn compare_trees(&self) -> Result<Option<(bool, usize)>, String> {
|
|
let (mut all_equal, mut cells) = (true, 0usize);
|
|
for tree in &self.opts.trees {
|
|
match self.compare_tree(tree)? {
|
|
TreeOutcome::Failed => return Ok(None),
|
|
TreeOutcome::Skipped => {}
|
|
TreeOutcome::Compared { cells: n, all_equal: eq } => {
|
|
cells += n;
|
|
all_equal &= eq;
|
|
}
|
|
}
|
|
}
|
|
Ok(Some((all_equal, cells)))
|
|
}
|
|
|
|
/// One tree: its process, then every case against the C++ reference.
|
|
fn compare_tree(&self, tree: &str) -> Result<TreeOutcome, String> {
|
|
let sibling = sibling_idle(self.opts.pin);
|
|
let res = self.run_tree_process(tree)?;
|
|
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" && self.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)"
|
|
);
|
|
return Ok(TreeOutcome::Skipped);
|
|
}
|
|
code => {
|
|
eprint!("{}", String::from_utf8_lossy(&res.stderr));
|
|
println!("tree {tree}: the Rust process failed (exit {code:?})");
|
|
return Ok(TreeOutcome::Failed);
|
|
}
|
|
}
|
|
println!(
|
|
"tree {tree}: {}",
|
|
report.iter().find(|l| l.starts_with("cpu: process kernel family")).map_or("", String::as_str)
|
|
);
|
|
self.compare_cases(&TreeCtx { tree, tree_name: static_tree(tree), report: &report, sibling })
|
|
}
|
|
|
|
fn compare_cases(&self, ctx: &TreeCtx) -> Result<TreeOutcome, String> {
|
|
let (mut all_equal, mut cells) = (true, 0usize);
|
|
for c in &self.verified.cases {
|
|
all_equal &= self.compare_case(c, ctx)?;
|
|
cells += 1;
|
|
}
|
|
Ok(TreeOutcome::Compared { cells, all_equal })
|
|
}
|
|
|
|
/// One case of one tree: compare our output file with the reference, print the verdict, write the record.
|
|
fn compare_case(&self, c: &CaseEntry, ctx: &TreeCtx) -> Result<bool, String> {
|
|
let tree = ctx.tree;
|
|
let ours_name = format!("case-{}.rust-{tree}.out", c.id);
|
|
let ours = read_out(&self.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 == ctx.tree_name).ok_or("missing reference out")?;
|
|
let reference = read_out(&self.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());
|
|
println!("case {} [{tree}] {}{}", c.id, case_label(c, &outcome), mismatch_detail(&outcome));
|
|
let record = record_json(&self.record_input(c, ctx, &outcome));
|
|
let path = self.records.join(format!("case-{}.{tree}.record.json", c.id));
|
|
fs::write(&path, record).map_err(|e| format!("{}: {e}", path.display()))?;
|
|
Ok(outcome.equal())
|
|
}
|
|
|
|
fn record_input<'r>(&'r self, c: &'r CaseEntry, ctx: &'r TreeCtx, outcome: &'r Outcome) -> RecordInput<'r> {
|
|
let tree = ctx.tree;
|
|
RecordInput {
|
|
record_id: format!(
|
|
"kab1-{}-{}-{tree}-{}",
|
|
self.verified.provenance.run_id,
|
|
c.id,
|
|
self.started.replace([':', '-'], "")
|
|
),
|
|
created_utc: now_utc(),
|
|
run_started_utc: self.started.clone(),
|
|
machine_role: self.machine_role.clone(),
|
|
cpu_model: cpu_model_of(ctx.report),
|
|
os: host_os(),
|
|
ours_compiler: self.tool.compiler.clone(),
|
|
ours_version: self.tool.version.clone(),
|
|
ours_triple: self.tool.triple.clone(),
|
|
ours_flags: self.tool.flags.clone(),
|
|
tree: ctx.tree_name,
|
|
verified: self.verified,
|
|
case: c,
|
|
pin_cpu: self.opts.pin,
|
|
sibling_idle: ctx.sibling,
|
|
outcome,
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Verifies the run directory and announces it; a refusal becomes the exit code (2 incomplete, 1 refused).
|
|
fn verify_and_announce(dir: &Path) -> Result<Verified, ExitCode> {
|
|
match verify_dir(dir) {
|
|
Ok(v) => {
|
|
println!(
|
|
"KAB1 directory verified: {} files, {} cases, manifest sha256 {}",
|
|
v.file_count,
|
|
v.cases.len(),
|
|
v.manifest_sha256
|
|
);
|
|
Ok(v)
|
|
}
|
|
Err(e) => {
|
|
println!("{e}");
|
|
Err(ExitCode::from(if e.incomplete { 2 } else { 1 }))
|
|
}
|
|
}
|
|
}
|
|
|
|
pub(super) fn cmd_compare(dir: &Path, opts: &Options) -> Result<ExitCode, String> {
|
|
let started = now_utc();
|
|
let verified = match verify_and_announce(dir) {
|
|
Ok(v) => v,
|
|
Err(code) => return Ok(code),
|
|
};
|
|
let run = CompareRun::new(dir, opts, &verified, started)?;
|
|
let Some((all_equal, cells)) = run.compare_trees()? else { return Ok(ExitCode::from(1)) };
|
|
println!(
|
|
"compared {cells} cells; records in {}; {}",
|
|
run.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,
|
|
}
|
|
}
|