STRA-338 size6 t01: split cmd_compare and the round records

This commit is contained in:
Pavlo Ratushnyi
2026-11-07 17:12:00 +01:00
parent b534afb99b
commit eb28be5059
3 changed files with 524 additions and 258 deletions
@@ -4,21 +4,47 @@
#[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
);
/// 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"))
@@ -29,113 +55,196 @@ pub(super) fn cmd_compare(dir: &Path, opts: &Options) -> Result<ExitCode, String
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}"))?;
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.
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" && verified.provenance.avx512_ok == Some(false) => {
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)"
);
continue;
return Ok(TreeOutcome::Skipped);
}
code => {
eprint!("{}", String::from_utf8_lossy(&res.stderr));
println!("tree {tree}: the Rust process failed (exit {code:?})");
return Ok(ExitCode::from(1));
return Ok(TreeOutcome::Failed);
}
}
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();
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;
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()))?;
}
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 {}; {}",
records.display(),
run.records.display(),
if all_equal { "ALL EQUAL" } else { "NOT ALL EQUAL" }
);
Ok(if all_equal && cells > 0 { ExitCode::SUCCESS } else { ExitCode::from(1) })
@@ -4,165 +4,8 @@
#[allow(unused_imports)]
use super::*;
/// 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.
pub(super) 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(&regime.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)
}
mod records;
pub(super) use records::round_records;
pub(super) fn aa_equality_block(o: &Outcome) -> String {
format!(
@@ -0,0 +1,314 @@
//! The records of one alternation round: per tree and regime the A/B record and the two A/A records, each written as
//! hand-made JSON in sections.
#[allow(unused_imports)]
use super::*;
/// What the records of a round need besides the processes: the batch, the round and the C++ toolchain.
struct RoundCtx<'a> {
ctx: &'a BatchCtx<'a>,
round_no: u32,
done: &'a [ProcOut],
cpp_tool: Tool,
gu: &'static str,
down: &'static str,
}
/// The four processes of one tree in a round.
struct TreeProcs<'a> {
tree: &'static str,
cpp_a: &'a ProcOut,
cpp_b: &'a ProcOut,
rust_a: &'a ProcOut,
rust_b: &'a ProcOut,
}
/// One record: the processes in the ours and the reference slot of a tree, regime and kind.
struct Pair<'a> {
tree: &'static str,
regime: &'static str,
kind: Kind,
ours: &'a ProcOut,
reference: &'a ProcOut,
ours_tool: &'a Tool,
ref_tool: &'a Tool,
}
impl Pair<'_> {
/// The statistics of the ours slot in this regime.
fn o(&self) -> &RegimeStat {
&self.ours.regimes[self.regime]
}
/// The statistics of the reference slot in this regime.
fn r(&self) -> &RegimeStat {
&self.reference.regimes[self.regime]
}
fn lower(&self) -> String {
self.regime.to_ascii_lowercase()
}
}
fn kind_text(kind: Kind) -> &'static str {
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)",
}
}
/// 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.
pub(crate) fn round_records(ctx: &BatchCtx, round_no: u32, done: &[ProcOut]) -> Result<Vec<(String, String)>, String> {
let p = &ctx.verified.provenance;
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 c = ctx.case;
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 rc = RoundCtx { ctx, round_no, done, cpp_tool, gu, down };
let mut files = Vec::new();
for tree in TREES.iter().copied().filter(|t| done.iter().any(|d| d.proc.tree == *t)) {
let procs = rc.tree_procs(tree)?;
for regime in ["RESIDENT", "STREAMED"] {
for kind in [Kind::Ab, Kind::AaCpp, Kind::AaRust] {
files.push(rc.record(&rc.pair(&procs, regime, kind))?);
}
}
}
Ok(files)
}
impl<'a> RoundCtx<'a> {
fn find(&self, imp: Impl, tree: &str, rep: char) -> Result<&'a ProcOut, String> {
let round_no = self.round_no;
self.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()))
}
fn tree_procs(&self, tree: &'static str) -> Result<TreeProcs<'a>, String> {
Ok(TreeProcs {
tree,
cpp_a: self.find(Impl::Cpp, tree, 'a')?,
cpp_b: self.find(Impl::Cpp, tree, 'b')?,
rust_a: self.find(Impl::Rust, tree, 'a')?,
rust_b: self.find(Impl::Rust, tree, 'b')?,
})
}
/// The processes and toolchains in the ours and the reference slot of `kind`.
fn pair<'p>(&'p self, procs: &TreeProcs<'p>, regime: &'static str, kind: Kind) -> Pair<'p> {
let rust = &self.ctx.rust_tool;
let (ours, reference, ours_tool, ref_tool) = match kind {
Kind::Ab => (procs.rust_a, procs.cpp_a, rust, &self.cpp_tool),
Kind::AaCpp => (procs.cpp_a, procs.cpp_b, &self.cpp_tool, &self.cpp_tool),
Kind::AaRust => (procs.rust_a, procs.rust_b, rust, rust),
};
Pair { tree: procs.tree, regime, kind, ours, reference, ours_tool, ref_tool }
}
/// The file name and the JSON of one record.
fn record(&self, pair: &Pair) -> Result<(String, String), String> {
self.check_stream(pair)?;
let (equality, equality_note) = self.equality(pair);
let kernel = self.kernel_text(pair, &equality_note);
let json = [
self.head(pair, &kernel),
self.toolchain(pair),
self.identity(pair),
self.clock(pair),
self.rows(pair),
self.noise_and_equality(&equality),
]
.concat();
let name = format!("r{:05}.{}.{}.{}.json", self.round_no, pair.kind.slug(), pair.tree, pair.lower());
Ok((name, json))
}
/// Both slots must have timed the same streamed set.
fn check_stream(&self, pair: &Pair) -> Result<(), String> {
let (o, r) = (pair.o(), pair.r());
if (o.copies_k, o.expert_bytes, o.llc_bytes) != (r.copies_k, r.expert_bytes, r.llc_bytes) {
let (round_no, tree, regime) = (self.round_no, pair.tree, pair.regime);
return Err(format!(
"round {round_no} {tree} {regime}: the streamed set differs between {} and {} (K {} vs {}, LLC {} vs \
{})",
pair.ours.proc.name(),
pair.reference.proc.name(),
o.copies_k,
r.copies_k,
o.llc_bytes,
r.llc_bytes
));
}
Ok(())
}
/// The equality block and the note that says where it comes from.
fn equality(&self, pair: &Pair) -> (String, String) {
let c = self.ctx.case;
match pair.kind {
Kind::Ab => (
equality_block(c, &self.ctx.equality[pair.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(pair.ours, pair.reference, c.rows);
(aa_equality_block(&outcome), format!("{note}, the same implementation in two fresh processes"))
}
}
}
fn kernel_text(&self, pair: &Pair, equality_note: &str) -> String {
let (c, gu, down, round_no) = (self.ctx.case, self.gu, self.down, self.round_no);
let regime = pair.regime;
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,
kind_text(pair.kind),
self.ctx.batch,
pair.ours.proc.name(),
pair.reference.proc.name(),
pair.ours.tree_text,
pair.reference.tree_text
)
}
/// Schema header, record id, timestamps, machine and the kernel description.
fn head(&self, pair: &Pair, kernel: &str) -> String {
let ctx = self.ctx;
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",
rid = jstr(&format!(
"kab1alt-{}-{}-b{}-r{:05}-{}-{}-{}",
ctx.verified.provenance.run_id,
ctx.case.id,
ctx.batch,
self.round_no,
pair.kind.slug(),
pair.tree,
pair.lower()
)),
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),
)
}
fn toolchain(&self, pair: &Pair) -> String {
format!(
" \"toolchain\": {{\n \"ours\": {ot},\n \"reference\": {rt}\n }},\n",
ot = tool_json(pair.ours_tool),
rt = tool_json(pair.ref_tool)
)
}
/// The streamed-set object of a STREAMED record (empty for RESIDENT).
fn streamed(&self, pair: &Pair) -> String {
let o = pair.o();
if pair.regime == "STREAMED" {
format!(
",\n \"streamed\": {{\"copies\": {}, \"expert_bytes\": {}, \"llc_bytes\": {}}}",
o.copies_k, o.expert_bytes, o.llc_bytes
)
} else {
String::new()
}
}
/// Case, hashes, tree, regime, pin and the upstream commit.
fn identity(&self, pair: &Pair) -> String {
let (ctx, c) = (self.ctx, self.ctx.case);
let streamed = self.streamed(pair);
let sibling_idle = pair.ours.sibling_idle == Some(true) && pair.reference.sibling_idle == Some(true);
format!(
" \"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",
cid = jstr(&c.id),
insha = jstr(&c.in_sha256),
msha = jstr(&ctx.verified.manifest_sha256),
tree_q = jstr(pair.tree),
regime_q = jstr(&pair.lower()),
pin = ctx.pin,
sib = sibling_idle,
commit = jstr(&ctx.verified.provenance.engine_strata_pin),
)
}
/// The two processes of a record, earliest first: the clock before the earlier one, after the later one.
fn earlier_later<'p>(&self, pair: &Pair<'p>) -> (&'p ProcOut, &'p ProcOut) {
let position = |p: &ProcOut| self.done.iter().position(|d| d.proc == p.proc).unwrap_or(0);
if position(pair.ours) <= position(pair.reference) {
(pair.ours, pair.reference)
} else {
(pair.reference, pair.ours)
}
}
fn clock(&self, pair: &Pair) -> String {
let (o, r) = (pair.o(), pair.r());
let (earlier, later) = self.earlier_later(pair);
format!(
" \"clock_calibration\": {{\"method\": {method}, \"ghz_before\": {g0}, \"ghz_after\": {g1}, \
\"max_drift_fraction\": {drift}, \"slices_total\": {total}, \"slices_dropped\": {dropped}}},\n",
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(o.max_drift.max(r.max_drift), 6),
total = o.requested + r.requested,
dropped = o.dropped + r.dropped,
)
}
/// The nanosecond and the cycle row.
fn rows(&self, pair: &Pair) -> String {
let (o, r, c) = (pair.o(), pair.r(), self.ctx.case);
let (gu, down, regime) = (self.gu, self.down, pair.lower());
let rowtype = |unit: &str| format!("{gu}+{down} rows={} {} [{unit}]", c.rows, regime);
format!(
" \"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",
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)),
)
}
/// The placeholder A/A noise floor and the equality block that closes the record.
fn noise_and_equality(&self, equality: &str) -> String {
format!(
" \"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"
)
}
}