diff --git a/crates/native-cpu-expert/examples/kernel_ab/cmd_alternate_fn.rs b/crates/native-cpu-expert/examples/kernel_ab/cmd_alternate_fn.rs index 81266af5..4b5a8926 100644 --- a/crates/native-cpu-expert/examples/kernel_ab/cmd_alternate_fn.rs +++ b/crates/native-cpu-expert/examples/kernel_ab/cmd_alternate_fn.rs @@ -1,24 +1,67 @@ //! Moved out of the parent module by STRA-338: fn cmd_alternate, fn usage. +use super::cmd_compare_fn::mismatch_detail; #[allow(unused_imports)] use super::*; -pub(super) fn cmd_alternate(args: &[String]) -> Result { - 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(); +mod batch; + +/// Where the batch writes and which executables it starts. +struct AltPaths { + out: PathBuf, + own_exe: PathBuf, + kab: PathBuf, +} + +/// The schedule as written before the first run and read back from the file. +struct Planned { + schedule: Vec<(u32, Vec)>, + text: String, + first_round: u32, +} + +/// The paths, the cells of a round and the schedule. +struct AltPlan { + paths: AltPaths, + trees: Vec<&'static str>, + procs: Vec, + planned: Planned, +} + +/// Facts about the host and the output directories, fixed for the whole batch. +struct AltHost { + records_dir: PathBuf, + proc_dir: PathBuf, + parent_env: Vec<(OsString, OsString)>, + sibling_at_start: bool, + machine_role: String, + rust_tool: Tool, +} + +/// One `alternate` batch. +struct AltRun { + a: AltArgs, + verified: Verified, + case: CaseEntry, + started: String, + plan: AltPlan, + host: AltHost, +} + +/// The C++ driver: `--kab`, else `$KAB`, else the build directory of the end-to-end root. +fn kab_path(a: &AltArgs) -> PathBuf { + 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") + }) +} + +/// The output directory, the two executables and the checks that keep generated files out of Git and out of the run +/// directory. +fn alt_paths(a: &AltArgs) -> Result { 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)) @@ -33,29 +76,22 @@ pub(super) fn cmd_alternate(args: &[String]) -> Result { ); } 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") - }); + let kab = kab_path(a); 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); + Ok(AltPaths { out, own_exe, kab }) +} - // the schedule, written BEFORE the first run and read back: the file, not the generator, drives the batch +/// The schedule, written BEFORE the first run and read back: the file, not the generator, drives the batch. +fn write_schedule(a: &AltArgs, out: &Path, procs: &[Proc]) -> Result { let first_round = (a.batch - 1) * a.rounds + 1; - let planned = make_schedule(a.seed, a.batch, a.rounds, &procs); + 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()))?; + 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()))?; } @@ -69,6 +105,20 @@ pub(super) fn cmd_alternate(args: &[String]) -> Result { schedule.len(), procs.len() ); + Ok(Planned { schedule, text, first_round }) +} + +fn plan_run(a: &AltArgs, verified: &Verified) -> Result { + let paths = alt_paths(a)?; + // 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); + let planned = write_schedule(a, &paths.out, &procs)?; + Ok(AltPlan { paths, trees, procs, planned }) +} + +fn probe_host(a: &AltArgs, out: &Path) -> Result { 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()))?; @@ -81,147 +131,169 @@ pub(super) fn cmd_alternate(args: &[String]) -> Result { .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 (version, triple) = rustc_info(); + let rust_tool = Tool { compiler: "rustc".to_owned(), version, triple, flags: ours_flags() }; + Ok(AltHost { records_dir, proc_dir, parent_env, sibling_at_start, machine_role, rust_tool }) +} - // 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 { +impl AltRun { + fn prepare(a: AltArgs, verified: Verified, started: String) -> Result { + 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 plan = plan_run(&a, &verified)?; + let host = probe_host(&a, &plan.paths.out)?; + Ok(Self { a, verified, case, started, plan, host }) + } + + /// Our tree against the C++ reference .out file, per tree, in fresh processes (the kernels are not touched by + /// timing). + fn equality_phase(&self) -> Result, String> { + let eq_dir = self.plan.paths.out.join(format!("equality-b{:04}", self.a.batch)); + let mut equality: BTreeMap<&'static str, Outcome> = BTreeMap::new(); + for tree in self.plan.trees.iter().copied() { + equality.insert(tree, self.equality_for(tree, &eq_dir)?); + } + Ok(equality) + } + + fn equality_for(&self, tree: &'static str, eq_dir: &Path) -> Result { + let (a, case) = (&self.a, &self.case); let p = Proc { imp: Impl::Rust, tree, rep: 'a' }; - let mut cmd = scrubbed_command(&own_exe, &parent_env, &cell_env(&p)); + let mut cmd = scrubbed_command(&self.plan.paths.own_exe, &self.host.parent_env, &cell_env(&p)); cmd.arg("run-tree") .arg(&a.dir) .args(["--tree", tree, "--case", &a.case, "--out"]) - .arg(&eq_dir) + .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 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 verdict = if outcome.equal() { "EQUAL" } else { "NOT_EQUAL" }; + println!("EQUALITY {} [{tree}] {verdict}{}", a.case, mismatch_detail(&outcome)); + Ok(outcome) } - let mut cpu_model = String::new(); - let batch_json = |cpu_model: String, equality: &BTreeMap<&'static str, Outcome>| -> Result { - 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::>() - .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::>() - .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)) - )) - }; + fn batch_ctx<'a>(&'a self, equality: &'a BTreeMap<&'static str, Outcome>) -> BatchCtx<'a> { + let (a, tool) = (&self.a, &self.host.rust_tool); + BatchCtx { + verified: &self.verified, + case: &self.case, + pin: a.pin, + machine_role: self.host.machine_role.clone(), + os: host_os(), + cpu_model: String::new(), + started_utc: self.started.clone(), + rust_tool: tool.clone(), + batch: a.batch, + equality, + } + } - 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 { + /// Every round of the schedule; returns the names of the records written. + fn rounds(&self, equality: &BTreeMap<&'static str, Outcome>) -> Result, String> { + let mut ctx = self.batch_ctx(equality); + let mut written = Vec::new(); + for (round_no, order) in &self.plan.planned.schedule { + let done = self.run_round(order, *round_no)?; + if ctx.cpu_model.is_empty() { + ctx.cpu_model = + done.iter().find_map(|d| d.cpu_model.clone()).unwrap_or_else(|| "unknown model".to_owned()); + let path = self.plan.paths.out.join(format!("batch-{:04}.json", self.a.batch)); + create_new_file(&path, self.batch_json(&ctx.cpu_model, equality)?.as_bytes())?; + } + for (name, json) in round_records(&ctx, *round_no, &done)? { + create_new_file(&self.host.records_dir.join(&name), json.as_bytes())?; + written.push(name); + } + println!("round {round_no} done: {}", order.iter().map(Proc::name).collect::>().join(" ")); + } + Ok(written) + } + + fn run_round(&self, order: &[Proc], round_no: u32) -> Result, String> { let mut done: Vec = 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)?); + done.push(self.run_proc(p, round_no)?); } - 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::>().join(" ")); + Ok(done) } - 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" }); + + /// The `time` command of one cell, writing its JSON to `file`. + fn cell_command(&self, p: &Proc, file: &Path) -> Command { + let (a, paths) = (&self.a, &self.plan.paths); + let mut cmd = scrubbed_command( + if p.imp == Impl::Cpp { &paths.kab } else { &paths.own_exe }, + &self.host.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()]); + } + cmd } + + fn run_proc(&self, p: &Proc, round_no: u32) -> Result { + let name = p.name(); + let file = self.host.proc_dir.join(format!("r{round_no:05}-{name}.json")); + let res = run_cell(&mut self.cell_command(p, &file), &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()))?; + let expect = Expect { + manifest_sha: &self.verified.manifest_sha256, + input_sha: &self.case.in_sha256, + case: &self.a.case, + pin: self.a.pin, + }; + parse_proc_json(p, &bytes, &expect) + } + + fn summarize(&self, written: &[String], equality: &BTreeMap<&'static str, Outcome>) { + let a = &self.a; + println!( + "ALTERNATE OK batch={} rounds={} records={} dir={}", + a.batch, + a.rounds, + written.len(), + self.host.records_dir.display() + ); + for (t, o) in equality { + println!("EQUALITY-SUMMARY {} {t} {}", a.case, if o.equal() { "EQUAL" } else { "NOT_EQUAL" }); + } + } +} + +pub(super) fn cmd_alternate(args: &[String]) -> Result { + 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 run = AltRun::prepare(a, verified, started)?; + let equality = run.equality_phase()?; + let written = run.rounds(&equality)?; + run.summarize(&written, &equality); Ok(ExitCode::SUCCESS) } @@ -229,13 +301,16 @@ pub(super) fn cmd_alternate(args: &[String]) -> Result { pub(super) 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]" + "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]" + " 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]" + " 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) } diff --git a/crates/native-cpu-expert/examples/kernel_ab/cmd_alternate_fn/batch.rs b/crates/native-cpu-expert/examples/kernel_ab/cmd_alternate_fn/batch.rs new file mode 100644 index 00000000..572d0e8d --- /dev/null +++ b/crates/native-cpu-expert/examples/kernel_ab/cmd_alternate_fn/batch.rs @@ -0,0 +1,99 @@ +//! The `batch-NNNN.json` file of an alternation batch, assembled in four consecutive sections. + +#[allow(unused_imports)] +use super::*; + +impl AltRun { + /// The batch description written once, with the first round (the CPU model comes from the first processes). + pub(super) fn batch_json( + &self, + cpu_model: &str, + equality: &BTreeMap<&'static str, Outcome>, + ) -> Result { + Ok([self.batch_run(), self.batch_machine(cpu_model), self.batch_files()?, self.batch_cells(equality)].concat()) + } + + /// Format, counts, run directory and the hashes of the manifest and of the case input. + fn batch_run(&self) -> String { + let (a, first_round) = (&self.a, self.plan.planned.first_round); + 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", + a.batch, + a.rounds, + jstr(&self.started), + jstr(&a.case), + jstr(&a.dir.display().to_string()), + jstr(&self.verified.manifest_sha256), + jstr(&self.case.in_sha256), + ) + } + + /// The pin, the pool, the machine and the seed. + fn batch_machine(&self, cpu_model: &str) -> String { + let (a, sibling_at_start) = (&self.a, self.host.sibling_at_start); + format!( + " \"pin\": {{\"logical_cpu\": {}, \"sibling_idle_at_start\": {sibling_at_start}}},\n \"pool\": \ + {{\"workers\": 1}},\n \"machine\": {{\"machine_role\": {}, \"cpu_model\": {}, \"os\": {}}},\n \"seed\": \ + {},\n", + a.pin, + jstr(&self.host.machine_role), + jstr(cpu_model), + jstr(&host_os()), + a.seed + ) + } + + /// The schedule file, the two executables with their hashes and the slice settings. + fn batch_files(&self) -> Result { + let (a, paths) = (&self.a, &self.plan.paths); + Ok(format!( + " \"schedule\": {{\"file\": {}, \"sha256\": {}}},\n \"kab\": {{\"path\": {}, \"sha256\": {}}},\n \ + \"rust_example\": {{\"path\": {}, \"sha256\": {}}},\n \"slices_per_regime\": {},\n \"slice_ms\": {},\n", + jstr(&a.schedule.display().to_string()), + jstr(&sha_hex(self.plan.planned.text.as_bytes())), + jstr(&paths.kab.display().to_string()), + jstr(&file_sha(&paths.kab)?), + jstr(&paths.own_exe.display().to_string()), + jstr(&file_sha(&paths.own_exe)?), + a.slices, + a.slice_ms.map_or("null".to_owned(), |m| jnum(m, 1)) + )) + } + + /// The equality verdicts per tree and the cells (processes) of a round. + fn batch_cells(&self, equality: &BTreeMap<&'static str, Outcome>) -> 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 self.case.tolerance.is_some() { "tolerance" } else { "bitwise" }, + o.compared, + o.mismatches + ) + }) + .collect::>() + .join(", "); + let cells = self.plan.procs.iter().map(|p| self.cell_json(p)).collect::>().join(", "); + format!( + " \"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" + ) + } + + fn cell_json(&self, p: &Proc) -> String { + 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()) + ) + } +} diff --git a/crates/native-cpu-expert/examples/kernel_ab/cmd_compare_fn.rs b/crates/native-cpu-expert/examples/kernel_ab/cmd_compare_fn.rs index 2028a952..7cb7a30f 100644 --- a/crates/native-cpu-expert/examples/kernel_ab/cmd_compare_fn.rs +++ b/crates/native-cpu-expert/examples/kernel_ab/cmd_compare_fn.rs @@ -1,23 +1,50 @@ -//! 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 .... +//! 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 { - 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 { 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")) @@ -28,112 +55,196 @@ pub(super) fn cmd_compare(dir: &Path, opts: &Options) -> Result = 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. +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 { + 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 { + 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, 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 { + 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 = 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)" + "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 { + 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 { + 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 { + 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 { + 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) }) @@ -172,9 +283,9 @@ pub(super) fn mono_ns() -> u64 { 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. +/// 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); diff --git a/crates/native-cpu-expert/examples/kernel_ab/cmd_time_fn.rs b/crates/native-cpu-expert/examples/kernel_ab/cmd_time_fn.rs index e594ab1b..8cc1eb71 100644 --- a/crates/native-cpu-expert/examples/kernel_ab/cmd_time_fn.rs +++ b/crates/native-cpu-expert/examples/kernel_ab/cmd_time_fn.rs @@ -3,12 +3,85 @@ #[allow(unused_imports)] use super::*; -/// `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. -pub(super) fn cmd_time(args: &[String]) -> Result { - 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 +mod doc; + +/// What the pinned CPU looked like before the run (read from sysfs and /proc, Linux only). +struct PinStart { + cpu_dir: String, + sib_text: String, + sibling: Option, + sib0: Option<(u64, u64)>, + pin0: Option<(u64, u64)>, + load0: String, +} + +/// What it looked like after the run, and the threads of the process with the CPU each last ran on. +struct PinEnd { + threads: Vec<(String, Option)>, + sib1: Option<(u64, u64)>, + pin1: Option<(u64, u64)>, +} + +/// The case of the run directory: the manifest hash, its entry and the verified input. +struct LoadedCase { + manifest_sha: String, + entry: CaseEntry, + case: CaseIn, +} + +impl LoadedCase { + /// The bytes of one expert (gate, up and down weights). + fn expert_bytes(&self) -> usize { + self.case.header.input_at() - IN_HEADER + } +} + +/// The managed environment, the kernel report and the tree of this process. +struct HostInfo { + env: BTreeMap, + report: Vec, + tree: &'static str, +} + +/// 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). +struct StreamPlan { + llc: Llc, + stride: usize, + copies_k: usize, +} + +/// Everything known before the first timed call. +struct TimeRun<'a> { + args: &'a [String], + t: TimeArgs, + wall0: u64, + start: PinStart, + loaded: LoadedCase, + host: HostInfo, + plan: StreamPlan, +} + +/// The timed regimes: JSON of each, whether all are ok, and the kept slices of the two regimes. +struct RegimeResults { + json: Vec, + all_ok: bool, + kept_res: usize, + kept_stm: usize, +} + +/// What the timed calls found. +struct Measured { + selfcheck: bool, + regimes: RegimeResults, + ghz: (f64, f64), + final_same: bool, + output_sha: String, +} + +/// Pins the process to `t.pin` before any buffer or pool exists (so the pool's threads inherit the mask), then +/// reads the facts about the pin. +fn pin_and_probe(t: &TimeArgs) -> Result { if rust_topology::pin_current_thread(t.pin as i32) < 0 { return Err(format!("the pin to CPU {} was refused", t.pin)); } @@ -21,23 +94,30 @@ pub(super) fn cmd_time(args: &[String]) -> Result { let sib0 = sibling.and_then(proc_stat_cpu); let pin0 = proc_stat_cpu(t.pin); let load0 = read_text("/proc/loadavg"); + Ok(PinStart { cpu_dir, sib_text, sibling, sib0, pin0, load0 }) +} - // the case: the KAB1 reader rule (validate, then use) and the manifest and case input hashes +/// The case: the KAB1 reader rule (validate, then use) and the manifest and case input hashes. +fn load_case(t: &TimeArgs) -> Result { 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(); + let entry = entry.clone(); + let case = read_case_in(&t.dir, &entry).map_err(|e| e.to_string())?; + Ok(LoadedCase { manifest_sha, entry, case }) +} - // environment and tree +/// The environment and the tree of this process. +fn host_info() -> Result { 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")?; + Ok(HostInfo { env, report, tree }) +} - // 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) +/// The last-level cache of the pinned CPU: the override of `--llc-bytes`, else sysfs. +fn llc_for(t: &TimeArgs) -> Result { 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() } @@ -50,198 +130,210 @@ pub(super) fn cmd_time(args: &[String]) -> Result { if llc.bytes == 0 { return Err("--llc-bytes must be positive".to_owned()); } + Ok(llc) +} + +fn plan_stream(t: &TimeArgs, expert_bytes: usize) -> Result { + let llc = llc_for(t)?; 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()); } + Ok(StreamPlan { llc, stride, copies_k }) +} - // 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 = want.iter().map(|v| v.to_bits()).collect(); - let output_sha = f32_bits_sha(&want); - - let mut tokens = Arena::::new(header.rows * H); - tokens.slice_mut(header.rows * H).copy_from_slice(&case.input()); - let mut resident = Arena::::new(stride); - resident.slice_mut(expert_bytes).copy_from_slice(weights); - let mut streamed = Arena::::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); +impl<'a> TimeRun<'a> { + fn prepare(args: &'a [String]) -> Result { + let t = parse_time_args(args)?; + let wall0 = mono_ns(); + let start = pin_and_probe(&t)?; + let loaded = load_case(&t)?; + let host = host_info()?; + let plan = plan_stream(&t, loaded.expert_bytes())?; + Ok(Self { args, t, wall0, start, loaded, host, plan }) } - 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 { + /// Writes the document by tmp + rename. + fn write_report(&self, end: &PinEnd, m: &Measured) -> Result<(), String> { + let j = doc::TimeDoc { run: self, end, m }.document(); + let t = &self.t; + 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())) + } + + /// Prints the summary line and maps the findings to the exit code. + fn finish(&self, m: &Measured) -> ExitCode { + let (t, tree, copies_k) = (&self.t, self.host.tree, self.plan.copies_k); + let (kept_res, kept_stm) = (m.regimes.kept_res, m.regimes.kept_stm); + 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 !m.regimes.all_ok { + eprintln!("kernel_ab time: a regime has no kept slice or a slice migrated off CPU {}", t.pin); + return ExitCode::from(3); + } + if !m.final_same { + eprintln!("kernel_ab time: the final output differs from the first call's"); + return ExitCode::from(4); + } + ExitCode::SUCCESS + } +} + +impl PinEnd { + fn read(run: &TimeRun) -> Self { + let threads = observed_threads(); + let sib1 = run.start.sibling.and_then(proc_stat_cpu); + let pin1 = proc_stat_cpu(run.t.pin); + Self { threads, sib1, pin1 } + } +} + +/// The aligned buffers of the run: the activations, the one resident expert copy and the K streamed copies. +struct Buffers { + tokens: Arena, + resident: Arena, + streamed: Arena, +} + +impl Buffers { + fn new(case: &CaseIn, plan: &StreamPlan) -> Self { + let header = case.header; + let weights = &case.blob[IN_HEADER..header.input_at()]; + let (expert_bytes, stride, all) = (weights.len(), plan.stride, plan.stride * plan.copies_k); + let mut tokens = Arena::::new(header.rows * H); + tokens.slice_mut(header.rows * H).copy_from_slice(&case.input()); + let mut resident = Arena::::new(stride); + resident.slice_mut(expert_bytes).copy_from_slice(weights); + let mut streamed = Arena::::new(all); + for k in 0..plan.copies_k { + streamed.slice_mut(all)[k * stride..k * stride + expert_bytes].copy_from_slice(weights); + } + Self { tokens, resident, streamed } + } +} + +/// The weight copies the timed calls cycle over, per regime. +struct CopySets<'a> { + resident: Vec<&'a [u8]>, + streamed: Vec<&'a [u8]>, + expert_bytes: usize, + plan: &'a StreamPlan, +} + +impl<'a> CopySets<'a> { + fn new(bufs: &'a Buffers, plan: &'a StreamPlan, expert_bytes: usize) -> Self { + let resident: Vec<&[u8]> = vec![bufs.resident.slice(expert_bytes)]; + let stm_all = bufs.streamed.slice(plan.stride * plan.copies_k); + let streamed: Vec<&[u8]> = + (0..plan.copies_k).map(|k| &stm_all[k * plan.stride..k * plan.stride + expert_bytes]).collect(); + Self { resident, streamed, expert_bytes, plan } + } + + /// The copies the selfcheck calls: the first resident one and the first and last streamed ones. + fn probes(&self) -> [&'a [u8]; 3] { + [self.resident[0], self.streamed[0], self.streamed[self.plan.copies_k - 1]] + } + + fn spec(&self, t: &TimeArgs, label: &'a str, copies: &[&'a [u8]], selfcheck: bool) -> RegimeSpec<'a> { + RegimeSpec { + label, + copies: copies.to_vec(), + expert_bytes: self.expert_bytes, + stride: self.plan.stride, + llc: &self.plan.llc, + slices: t.slices, + slice_ms: t.slice_ms, + pin: t.pin, + selfcheck, + } + } +} + +fn new_timed(pool: DirectCpuPool, header: InHeader, tokens: &[f32]) -> Result, String> { + Ok(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), + tokens, 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 + }) +} + +fn same_bits(out: &[f32], want_bits: &[u32]) -> bool { + out.iter().map(|v| v.to_bits()).eq(want_bits.iter().copied()) +} + +/// The timed call's output on every aligned copy is bit-identical to the first (unaligned) call's. +fn selfcheck(timed: &mut Timed, want_bits: &[u32], weights: [&[u8]; 3]) -> Result { let mut selfcheck = true; - for w in [res_copies[0], stm_copies[0], stm_copies[copies_k - 1]] { + for w in weights { timed.call(w)?; - selfcheck &= timed.out.iter().map(|v| v.to_bits()).eq(want_bits.iter().copied()); + selfcheck &= same_bits(&timed.out, want_bits); } if !selfcheck { return Err("selfcheck failed: the timed call differs from the first call".to_owned()); } + Ok(selfcheck) +} - let ghz0 = core_ghz(); - let mut regimes = Vec::new(); - let mut all_ok = true; - let (mut kept_res, mut kept_stm) = (0, 0); +fn run_regimes(t: &TimeArgs, timed: &mut Timed, sets: &CopySets, selfcheck: bool) -> Result { + let mut res = RegimeResults { json: Vec::new(), all_ok: true, kept_res: 0, kept_stm: 0 }; for (label, copies, sel) in - [("RESIDENT", &res_copies, RegimeSel::Resident), ("STREAMED", &stm_copies, RegimeSel::Streamed)] + [("RESIDENT", &sets.resident, RegimeSel::Resident), ("STREAMED", &sets.streamed, 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; + let r = run_regime(timed, &sets.spec(t, label, copies, selfcheck))?; + res.all_ok &= r.ok; if sel == RegimeSel::Resident { - kept_res = r.kept + res.kept_res = r.kept } else { - kept_stm = r.kept + res.kept_stm = r.kept } - regimes.push(r.json); + res.json.push(r.json); } + Ok(res) +} + +/// The selfcheck, the two calibrated regimes and the final unchanged-output check. +fn measure(run: &TimeRun, pool: DirectCpuPool, want: &[f32]) -> Result { + let (header, expert_bytes) = (run.loaded.case.header, run.loaded.expert_bytes()); + let want_bits: Vec = want.iter().map(|v| v.to_bits()).collect(); + let bufs = Buffers::new(&run.loaded.case, &run.plan); + let mut timed = new_timed(pool, header, bufs.tokens.slice(header.rows * H))?; + let sets = CopySets::new(&bufs, &run.plan, expert_bytes); + let selfcheck = selfcheck(&mut timed, &want_bits, sets.probes())?; + let ghz0 = core_ghz(); + let regimes = run_regimes(&run.t, &mut timed, &sets, selfcheck)?; 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()); + timed.call(sets.resident[0])?; + let final_same = same_bits(&timed.out, &want_bits); + Ok(Measured { selfcheck, regimes, ghz: (ghz0, ghz1), final_same, output_sha: f32_bits_sha(want) }) +} - let threads = observed_threads(); - let sib1 = sibling.and_then(proc_stat_cpu); - let pin1 = proc_stat_cpu(t.pin); - let frac = |f: Option| 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::>().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::>() - .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) +/// `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. +pub(super) fn cmd_time(args: &[String]) -> Result { + let run = TimeRun::prepare(args)?; + // 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, &run.loaded.case)?; + let m = measure(&run, pool, &want)?; + let end = PinEnd::read(&run); + run.write_report(&end, &m)?; + Ok(run.finish(&m)) } diff --git a/crates/native-cpu-expert/examples/kernel_ab/cmd_time_fn/doc.rs b/crates/native-cpu-expert/examples/kernel_ab/cmd_time_fn/doc.rs new file mode 100644 index 00000000..2c8ee495 --- /dev/null +++ b/crates/native-cpu-expert/examples/kernel_ab/cmd_time_fn/doc.rs @@ -0,0 +1,190 @@ +//! The KAB1-time JSON document of `kernel_ab time`, assembled in ten consecutive sections. + +#[allow(unused_imports)] +use super::*; + +/// The three inputs of the document besides the run itself: the pin facts after the run and the measurements. +pub(super) struct TimeDoc<'a> { + pub(super) run: &'a TimeRun<'a>, + pub(super) end: &'a PinEnd, + pub(super) m: &'a Measured, +} + +fn frac(f: Option) -> String { + f.map_or("null".to_owned(), |v| jnum(v, 4)) +} + +impl TimeDoc<'_> { + /// The whole document: the sections follow each other in the order of the file. + pub(super) fn document(&self) -> String { + [ + String::from( + "{\n \"format\": \"KAB1-time\",\n \"version\": 1,\n \"mode\": \"time\",\n \"writer\": \"rust\",\n", + ), + self.run_info(), + self.case_json(), + self.tree_json(), + self.pool_json(), + self.pin_json(), + self.buffers_json(), + self.clock_json(), + self.build_json(), + self.tail_json(), + ] + .concat() + } + + /// The command line as `kab time` would have been given it. + fn command_line(&self) -> String { + let (t, args) = (&self.run.t, self.run.args); + 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(), + } + ) + } + + fn run_info(&self) -> String { + let t = &self.run.t; + format!( + " \"command_line\": {},\n \"run_dir\": {},\n \"manifest_sha256\": {},\n", + jstr(&self.command_line()), + jstr(&t.dir.display().to_string()), + jstr(&self.run.loaded.manifest_sha) + ) + } + + fn case_json(&self) -> String { + let (t, loaded) = (&self.run.t, &self.run.loaded); + let header = loaded.case.header; + 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); + 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(&loaded.entry.in_sha256), + loaded.expert_bytes() + ) + } + + fn tree_json(&self) -> String { + let host = &self.run.host; + format!( + " \"tree\": {},\n \"tree_detail\": {{\"tree\": {}, \"cpu_report\": [{}], \"strata_env\": {}}},\n \ + \"effective_env\": {},\n", + jstr(host.tree), + jstr(host.tree), + host.report.iter().map(|l| jstr(l)).collect::>().join(", "), + json_env(&host.env), + json_env(&host.env) + ) + } + + fn pool_json(&self) -> String { + 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", + self.end + .threads + .iter() + .map(|(n, c)| format!( + "{{\"name\": {}, \"cpu\": {}}}", + jstr(n), + c.map_or("null".to_owned(), |c| c.to_string()) + )) + .collect::>() + .join(", ") + ) + } + + fn pin_json(&self) -> String { + let (start, end) = (&self.run.start, self.end); + let (cpu_dir, sibling) = (&start.cpu_dir, start.sibling); + 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", + self.run.t.pin, + jstr(&start.sib_text), + sibling.map_or("null".to_owned(), |s| s.to_string()), + jstr(&read_text(&format!("{cpu_dir}/topology/core_id"))), + frac(busy_fraction(start.pin0, end.pin1)), + if sibling.is_some() { frac(busy_fraction(start.sib0, end.sib1)) } else { "null".to_owned() }, + jstr(&read_text(&format!("{cpu_dir}/cpufreq/scaling_governor"))), + jstr(&read_text("/sys/devices/system/cpu/cpufreq/boost")), + jstr(&start.load0), + jstr(&read_text("/proc/loadavg")), + current_cpu().map_or("null".to_owned(), |c| c.to_string()) + ) + } + + fn buffers_json(&self) -> String { + let stride = self.run.plan.stride; + 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" + ) + } + + fn clock_json(&self) -> String { + 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(self.m.ghz.0, 6), + jnum(self.m.ghz.1, 6) + ) + } + + fn build_json(&self) -> String { + 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()) + ) + } + + fn tail_json(&self) -> String { + let (selfcheck, final_same) = (self.m.selfcheck, self.m.final_same); + 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(&self.m.output_sha), + mono_ns() - self.run.wall0, + self.m.regimes.json.join(",\n ") + ) + } +} diff --git a/crates/native-cpu-expert/examples/kernel_ab/describe_cpp_tree_fn.rs b/crates/native-cpu-expert/examples/kernel_ab/describe_cpp_tree_fn.rs index b291242b..d5c12c03 100644 --- a/crates/native-cpu-expert/examples/kernel_ab/describe_cpp_tree_fn.rs +++ b/crates/native-cpu-expert/examples/kernel_ab/describe_cpp_tree_fn.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: fn describe_cpp_tree, fn parse_proc_json, impl Kind, fn side_stat, fn stat_json, fn tool_json .... +//! Moved out of the parent module by STRA-338: fn describe_cpp_tree, fn parse_proc_json, impl Kind, fn side_stat, fn +//! stat_json, fn tool_json .... #[allow(unused_imports)] use super::*; @@ -28,43 +29,80 @@ pub(super) fn describe_cpp_tree(d: &Json) -> String { ) } -/// 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. +/// 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. pub(super) fn parse_proc_json(p: &Proc, bytes: &[u8], expect: &Expect) -> Result { 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())); + proc_out(&j, p, expect).map_err(|what| format!("cell {name}: {what}")) +} + +/// The body of `parse_proc_json`; every error text is still to be prefixed with the cell name by the caller. +fn proc_out(j: &Json, p: &Proc, expect: &Expect) -> Result { + let pin = check_proc_json(j, p, expect)?; + let (regimes, clock) = read_regimes_and_clock(j, p)?; + let sibling_idle = sibling_idle_of(pin)?; + let (tree_text, cpu_model) = tree_report(j.req("tree_detail")?, p)?; + Ok(ProcOut { + proc: *p, + regimes, + ghz_start: clock.float("ghz_at_start")?, + ghz_end: clock.float("ghz_at_end")?, + sibling_idle, + final_unchanged: j.flag("final_output_unchanged")?, + output_sha: j.get("output_sha256").and_then(|v| if let Json::Str(s) = v { Some(s.clone()) } else { None }), + tree_text, + cpu_model, + }) +} + +/// The identity of the output against the cell and the run; returns the `pin` object for the later reads. +fn check_proc_json<'j>(j: &'j Json, p: &Proc, expect: &Expect) -> Result<&'j Json, String> { + check_identity(j, p)?; + check_manifest_case(j, expect)?; + check_pin_env(j, p, expect) +} + +fn check_identity(j: &Json, p: &Proc) -> Result<(), String> { + if j.str("format")? != "KAB1-time" || j.uint("version")? != 1 { + return Err("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("writer")? != p.imp.name() { + return Err(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("tree")? != p.tree { + return Err(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())); + Ok(()) +} + +fn check_manifest_case(j: &Json, expect: &Expect) -> Result<(), String> { + if j.str("manifest_sha256")? != expect.manifest_sha { + return Err("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 c = j.req("case")?; + if c.str("id")? != expect.case || c.str("input_sha256")? != expect.input_sha { + return Err("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))); + Ok(()) +} + +fn check_pin_env<'j>(j: &'j Json, p: &Proc, expect: &Expect) -> Result<&'j Json, String> { + let pin = j.req("pin")?; + if pin.uint("cpu")? as usize != expect.pin { + return Err(format!("pinned to CPU {}, expected {}", pin.uint("cpu").unwrap_or(u64::MAX), expect.pin)); } let want_env: BTreeMap = cell_env(p).into_iter().collect(); + let seen_env = effective_env(j)?; + if seen_env != want_env { + return Err(format!("effective environment {seen_env:?} differs from the cell's {want_env:?}")); + } + Ok(pin) +} + +fn effective_env(j: &Json) -> Result, String> { let mut seen_env = BTreeMap::new(); - if let Json::Obj(items) = j.req("effective_env").map_err(fail)? { + if let Json::Obj(items) = j.req("effective_env")? { for (k, v) in items { seen_env.insert( k.clone(), @@ -76,54 +114,52 @@ pub(super) fn parse_proc_json(p: &Proc, bytes: &[u8], expect: &Expect) -> Result ); } } - if seen_env != want_env { - return Err(fail(format!("effective environment {seen_env:?} differs from the cell's {want_env:?}"))); - } + Ok(seen_env) +} + +/// The per-regime statistics (both regimes must be present) and the `clock_calibration` object. +fn read_regimes_and_clock<'j>(j: &'j Json, p: &Proc) -> Result<(BTreeMap, &'j Json), String> { 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 r in j.array("regimes")? { + let label = r.str("regime")?.to_owned(); + regimes.insert(label, parse_regime(r, p.imp)?); } for want in ["RESIDENT", "STREAMED"] { if !regimes.contains_key(want) { - return Err(fail(format!("regime {want} is missing"))); + return Err(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)? { + Ok((regimes, j.req("clock_calibration")?)) +} + +fn sibling_idle_of(pin: &Json) -> Result, String> { + Ok(match pin.req("sibling_cpu")? { 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 = 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, + _ => pin.float_or_null("sibling_busy_fraction_during_run")?.map(|f| f < SIBLING_BUSY_LIMIT), }) } + +/// The tree text of the record and the CPU model (only a Rust process reports one). +fn tree_report(detail: &Json, p: &Proc) -> Result<(String, Option), String> { + let (tree_text, cpu_report) = + if p.imp == Impl::Rust { rust_tree_report(detail)? } else { (describe_cpp_tree(detail), Vec::new()) }; + let cpu_model = (!cpu_report.is_empty()).then(|| cpu_model_of(&cpu_report)); + Ok((tree_text, cpu_model)) +} + +fn rust_tree_report(detail: &Json) -> Result<(String, Vec), String> { + let report: Vec = detail + .array("cpu_report")? + .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(|| "no process kernel family line".to_owned())?; + Ok((format!("leleka-serve {line}"), report)) +} impl Kind { pub(super) fn slug(self) -> &'static str { match self { @@ -167,7 +203,8 @@ pub(super) fn equality_block(c: &CaseEntry, o: &Outcome) -> String { ) }); format!( - "{{\n \"mode\": \"{}\",\n \"verdict\": \"{}\",\n \"compared_values\": {},\n \"mismatches\": {}{tolerance}\n }}", + "{{\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, @@ -175,8 +212,9 @@ pub(super) fn equality_block(c: &CaseEntry, o: &Outcome) -> String { ) } -/// 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. +/// 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. pub(super) fn aa_outcome(a: &ProcOut, b: &ProcOut, rows: usize) -> (Outcome, String) { let compared = rows * H; let selfchecks = diff --git a/crates/native-cpu-expert/examples/kernel_ab/gate_up_row_fn.rs b/crates/native-cpu-expert/examples/kernel_ab/gate_up_row_fn.rs index cf075fd3..a6a7a703 100644 --- a/crates/native-cpu-expert/examples/kernel_ab/gate_up_row_fn.rs +++ b/crates/native-cpu-expert/examples/kernel_ab/gate_up_row_fn.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: fn gate_up_row, fn down_row, impl Refusal, impl std_fmt_Display, fn sha_hex, fn take_buffer .... +//! Moved out of the parent module by STRA-338: fn gate_up_row, fn down_row, impl Refusal, impl std_fmt_Display, fn +//! sha_hex, fn take_buffer .... #[allow(unused_imports)] use super::*; diff --git a/crates/native-cpu-expert/examples/kernel_ab/impl_impl.rs b/crates/native-cpu-expert/examples/kernel_ab/impl_impl.rs index a50737c4..62a306a3 100644 --- a/crates/native-cpu-expert/examples/kernel_ab/impl_impl.rs +++ b/crates/native-cpu-expert/examples/kernel_ab/impl_impl.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl Impl, impl Proc, fn procs_for, fn cell_env, fn scrubbed_command, fn run_cell .... +//! Moved out of the parent module by STRA-338: impl Impl, impl Proc, fn procs_for, fn cell_env, fn scrubbed_command, fn +//! run_cell .... #[allow(unused_imports)] use super::*; @@ -46,10 +47,12 @@ pub(super) fn procs_for(trees: &[&'static str]) -> Vec { 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). +/// 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). pub(super) fn cell_env(p: &Proc) -> Vec<(String, String)> { let mut v = Vec::new(); if p.tree == "avx2" { @@ -63,7 +66,8 @@ pub(super) fn cell_env(p: &Proc) -> Vec<(String, String)> { v } -/// A command whose environment is exactly: the parent's variables minus every STRATA_* / LELEKA_* one, plus the cell's variables. +/// A command whose environment is exactly: the parent's variables minus every STRATA_* / LELEKA_* one, plus the cell's +/// variables. pub(super) fn scrubbed_command( program: &Path, parent_env: &[(OsString, OsString)], @@ -115,8 +119,9 @@ pub(super) fn splitmix(state: &mut u64) -> u64 { 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). +/// 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). pub(super) fn make_schedule(seed: u64, batch: u32, rounds: u32, procs: &[Proc]) -> Vec> { let n = procs.len(); let mut out = Vec::new(); @@ -151,7 +156,8 @@ pub(super) fn schedule_text( order: &[Vec], ) -> 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" + "{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::>().join(",")); @@ -159,7 +165,8 @@ pub(super) fn schedule_text( t } -/// Reads a schedule back: (round number, processes in order) per round. Every round must name each process of the first round once. +/// Reads a schedule back: (round number, processes in order) per round. Every round must name each process of the first +/// round once. pub(super) fn parse_schedule(text: &str) -> Result)>, String> { let mut lines = text.lines(); if !lines.next().is_some_and(|l| l.starts_with(SCHEDULE_MAGIC)) { @@ -167,16 +174,9 @@ pub(super) fn parse_schedule(text: &str) -> Result)>, String } let mut rounds: Vec<(u32, Vec)> = 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::().map_err(|_| format!("bad round number in {l:?}"))?; - let order: Vec = list - .split(',') - .map(|n| Proc::parse(n).ok_or_else(|| format!("unknown process {n:?} in the schedule"))) - .collect::>()?; + let (no, order) = parse_schedule_line(l)?; 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()) + && !round_follows(prev, no, &order) { return Err(format!("round {no} does not follow round {} with the same processes", prev.0)); } @@ -188,34 +188,74 @@ pub(super) fn parse_schedule(text: &str) -> Result)>, String Ok(rounds) } +/// One schedule line: the round number, a tab, the comma-separated processes. +fn parse_schedule_line(l: &str) -> Result<(u32, Vec), String> { + let (no, list) = l.split_once('\t').ok_or_else(|| format!("bad schedule line {l:?}"))?; + let no = no.parse::().map_err(|_| format!("bad round number in {l:?}"))?; + let order: Vec = list + .split(',') + .map(|n| Proc::parse(n).ok_or_else(|| format!("unknown process {n:?} in the schedule"))) + .collect::>()?; + Ok((no, order)) +} + +/// Round `no` follows `prev`: the next number and the same set of processes. +fn round_follows(prev: &(u32, Vec), no: u32, order: &[Proc]) -> bool { + no == prev.0 + 1 + && BTreeSet::from_iter(order.iter()) == BTreeSet::from_iter(prev.1.iter()) + && order.len() == prev.1.len() +} + /// Refuses a path that is, or lies inside, a Git checkout (generated artifacts stay out of Git). pub(super) 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()) } -pub(super) fn parse_regime(r: &Json, imp: Impl) -> Result { - let mut ns = Vec::new(); - let mut cycles = Vec::new(); - let mut max_drift = 0.0f64; +/// The slice series of one regime: the kept slices' timings and the largest clock drift over kept and dropped slices. +struct SliceSeries { + ns: Vec, + cycles: Vec, + max_drift: f64, +} + +fn read_slice(s: &Json, keep: bool, acc: &mut SliceSeries) -> Result<(), String> { + let (g0, g1) = (s.float("ghz_before")?, s.float("ghz_after")?); + if g0 > 0.0 { + acc.max_drift = acc.max_drift.max(((g1 - g0).abs() / g0).min(1.0)); + } + if keep { + acc.ns.push(s.float("ns_per_call")?); + acc.cycles.push(s.float("cycles_per_call")?); + } + Ok(()) +} + +fn read_series(r: &Json) -> Result { + let mut acc = SliceSeries { ns: Vec::new(), cycles: Vec::new(), 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")?); - } + read_slice(s, keep, &mut acc)?; } } + Ok(acc) +} + +pub(super) fn parse_regime(r: &Json, imp: Impl) -> Result { + let series = read_series(r)?; 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())); + if kept != series.ns.len() || kept == 0 { + return Err(format!( + "slices_kept {kept} disagrees with the {} kept slices (or none was kept)", + series.ns.len() + )); } + regime_stat(r, series, selfcheck_key) +} + +fn regime_stat(r: &Json, series: SliceSeries, selfcheck_key: &str) -> Result { Ok(RegimeStat { copies_k: r.uint("copies_k")? as usize, expert_bytes: r.uint("expert_bytes")? as usize, @@ -224,9 +264,9 @@ pub(super) fn parse_regime(r: &Json, imp: Impl) -> Result { 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, + ns: series.ns, + cycles: series.cycles, + max_drift: series.max_drift, selfcheck: r.flag(selfcheck_key)?, }) } diff --git a/crates/native-cpu-expert/examples/kernel_ab/impl_parser.rs b/crates/native-cpu-expert/examples/kernel_ab/impl_parser.rs index 8c356062..ef00f151 100644 --- a/crates/native-cpu-expert/examples/kernel_ab/impl_parser.rs +++ b/crates/native-cpu-expert/examples/kernel_ab/impl_parser.rs @@ -38,39 +38,7 @@ impl Parser<'_> { 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 ch = self.escape()?; let mut buf = [0u8; 4]; out.extend_from_slice(ch.encode_utf8(&mut buf).as_bytes()); } @@ -79,6 +47,38 @@ impl Parser<'_> { } } } + /// The character after a backslash (the cursor is on the escape letter). + fn escape(&mut self) -> Result { + let Some(&e) = self.b.get(self.at) else { return self.err("unterminated escape") }; + self.at += 1; + if e == b'u' { + return self.unicode_escape(); + } + match simple_escape(e) { + Some(ch) => Ok(ch), + None => self.err("unknown escape"), + } + } + fn unicode_escape(&mut self) -> Result { + let hi = self.hex4()?; + let cp = if (0xD800..0xDC00).contains(&hi) { self.low_surrogate(hi)? } else { hi }; + match char::from_u32(cp) { + Some(c) => Ok(c), + None => self.err("lone surrogate"), + } + } + /// The code point of a surrogate pair whose high half `hi` was read. + fn low_surrogate(&mut self, hi: u32) -> Result { + 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"); + } + Ok(0x10000 + ((hi - 0xD800) << 10) + (lo - 0xDC00)) + } pub(super) fn number(&mut self) -> Result { 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') { @@ -97,63 +97,9 @@ impl Parser<'_> { 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'{') => self.object(depth), + Some(b'[') => self.array(depth), + Some(b'"') => self.string().map(Json::Str), 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), @@ -161,6 +107,86 @@ impl Parser<'_> { Some(_) => self.err("unexpected character"), } } + fn object(&mut self, depth: usize) -> Result { + 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 { + let member = self.member(&items, depth)?; + items.push(member); + if self.separator(b'}', "',' or '}' expected")? { + return Ok(Json::Obj(items)); + } + } + } + /// One `"key": value` pair of an object; a repeated key is refused. + fn member(&mut self, items: &[(String, Json)], depth: usize) -> Result<(String, Json), String> { + 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)?; + Ok((key, v)) + } + fn array(&mut self, depth: usize) -> Result { + 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)?); + if self.separator(b']', "',' or ']' expected")? { + return Ok(Json::Arr(items)); + } + } + } + /// After an element: a comma continues (false), the closing byte ends the container (true), anything else is + /// `expected`. + fn separator(&mut self, close: u8, expected: &str) -> Result { + self.ws(); + match self.b.get(self.at) { + Some(b',') => { + self.at += 1; + Ok(false) + } + Some(&c) if c == close => { + self.at += 1; + Ok(true) + } + _ => self.err(expected), + } + } +} + +/// The character of a single-letter escape (`\n`, `\t`, ...), None for an unknown letter. +fn simple_escape(e: u8) -> Option { + Some(match e { + b'"' => '"', + b'\\' => '\\', + b'/' => '/', + b'b' => '\u{8}', + b'f' => '\u{c}', + b'n' => '\n', + b'r' => '\r', + b't' => '\t', + _ => return None, + }) } pub(super) fn parse_json(bytes: &[u8]) -> Result { diff --git a/crates/native-cpu-expert/examples/kernel_ab/in_magic_types.rs b/crates/native-cpu-expert/examples/kernel_ab/in_magic_types.rs index dbaa205d..05040901 100644 --- a/crates/native-cpu-expert/examples/kernel_ab/in_magic_types.rs +++ b/crates/native-cpu-expert/examples/kernel_ab/in_magic_types.rs @@ -15,8 +15,9 @@ pub(super) const MAX_FILE_BYTES: u64 = 16 << 20; pub(super) const MAX_MANIFEST_BYTES: u64 = 8 << 20; pub(super) const MAX_CASES: usize = 1024; pub(super) 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. +/// 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. pub(super) const NOT_MEASURED: &str = "NOT_MEASURED (filled by STRA-318, the alternation runner)"; pub(super) const TREES: [&str; 2] = ["avx512", "avx2"]; @@ -173,23 +174,27 @@ pub(super) struct Options { pub(super) case: Option, } -// ------------------------------------------------------------------------------------------------ flags (time, alternate) +// --------------------------------------------------------------------------------- flags (time, alternate) pub(super) struct Flags(pub(super) Vec<(String, String)>); -// ------------------------------------------------------------------------------------------------ clocks and host facts +// ----------------------------------------------------------------------------------- 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. pub(super) 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. +/// `tq_cpu_parity.cpp:303`: a slice whose calibrated clock moved by more than this fraction is dropped. Copied, not +/// chosen here. pub(super) const CLOCK_MOVED_FRACTION: f64 = 0.05; /// An SMT sibling busier than this fraction is not idle (the 5 percent rule of `sibling_idle`). pub(super) const SIBLING_BUSY_LIMIT: f64 = 0.05; pub(super) 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. +/// 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. pub(super) const CHAIN_STEP_CYCLES: f64 = 4.0; -pub(super) 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"; +pub(super) const CLOCK_METHOD: &str = concat!( + "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" +); pub(super) struct Llc { pub(super) level: u32, @@ -197,7 +202,7 @@ pub(super) struct Llc { pub(super) source: String, } -// ------------------------------------------------------------------------------------------------ time (one fresh process) +// -------------------------------------------------------------------------------- time (one fresh process) #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub(super) enum RegimeSel { diff --git a/crates/native-cpu-expert/examples/kernel_ab/llc_of_cpu_fn.rs b/crates/native-cpu-expert/examples/kernel_ab/llc_of_cpu_fn.rs index 0153266e..6a570498 100644 --- a/crates/native-cpu-expert/examples/kernel_ab/llc_of_cpu_fn.rs +++ b/crates/native-cpu-expert/examples/kernel_ab/llc_of_cpu_fn.rs @@ -1,9 +1,11 @@ -//! Moved out of the parent module by STRA-338: fn llc_of_cpu, fn proc_stat_cpu, fn busy_fraction, fn current_cpu, fn observed_threads, fn is_managed_name .... +//! Moved out of the parent module by STRA-338: fn llc_of_cpu, fn proc_stat_cpu, fn busy_fraction, fn current_cpu, fn +//! observed_threads, fn is_managed_name .... #[allow(unused_imports)] use super::*; -/// Linux: the highest-level data or unified cache of `cpu` from sysfs. Elsewhere: None (the caller passes `--llc-bytes`). +/// Linux: the highest-level data or unified cache of `cpu` from sysfs. Elsewhere: None (the caller passes +/// `--llc-bytes`). pub(super) fn llc_of_cpu(cpu: usize) -> Option { let mut best: Option = None; for i in 0..16 { @@ -82,21 +84,8 @@ pub(super) fn json_env(env: &BTreeMap) -> String { /// The command line of `kab time` (STRA-317), checked the same way. pub(super) fn parse_time_args(args: &[String]) -> Result { let f = Flags::parse(args, &TIME_FLAGS)?; - let slices = f.number::("slices")?.ok_or("--slices is required")?; - let pin = f.number::("pin")?.ok_or("--pin is required")?; - let slice_ms = f.number::("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 (slices, pin, slice_ms) = time_counts(&f)?; + let regime = parse_regime_sel(f.get("regime").unwrap_or("both"))?; let case = f.req("case")?.to_owned(); if !valid_id(&case) { return Err(format!("--case {case:?} is not a plain identifier")); @@ -112,6 +101,29 @@ pub(super) fn parse_time_args(args: &[String]) -> Result { llc_bytes: f.number::("llc-bytes")?, }) } + +/// `--slices`, `--pin` and `--slice-ms`, range checked. +fn time_counts(f: &Flags) -> Result<(usize, usize, f64), String> { + let slices = f.number::("slices")?.ok_or("--slices is required")?; + let pin = f.number::("pin")?.ok_or("--pin is required")?; + let slice_ms = f.number::("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()); + } + Ok((slices, pin, slice_ms)) +} + +fn parse_regime_sel(s: &str) -> Result { + match s { + "both" => Ok(RegimeSel::Both), + "resident" => Ok(RegimeSel::Resident), + "streamed" => Ok(RegimeSel::Streamed), + _ => Err("--regime must be both, resident or streamed".to_owned()), + } +} impl Arena { pub(super) fn new(len: usize) -> Self { let size = std::mem::size_of::(); @@ -145,7 +157,8 @@ impl Timed<'_> { } } -/// One slice of `ms` milliseconds cycling over the copies; the shape of `time_slice()` in tq_cpu_parity.cpp (lines 290-304). +/// One slice of `ms` milliseconds cycling over the copies; the shape of `time_slice()` in tq_cpu_parity.cpp (lines +/// 290-304). pub(super) fn time_slice(t: &mut Timed, copies: &[&[u8]], ms: f64, next: &mut usize) -> Result { let ghz_before = core_ghz(); let mut calls = 0u64; @@ -177,7 +190,8 @@ pub(super) fn time_slice(t: &mut Timed, copies: &[&[u8]], ms: f64, next: &mut us pub(super) fn slice_json(s: &Slice, idx: usize) -> String { format!( - "{{\"i\": {idx}, \"calls\": {}, \"wall_ns\": {}, \"ns_per_call\": {}, \"ghz_before\": {}, \"ghz_after\": {}, \"cycles_per_call\": {}}}", + "{{\"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), diff --git a/crates/native-cpu-expert/examples/kernel_ab/main.rs b/crates/native-cpu-expert/examples/kernel_ab/main.rs index 0242a9e3..c4c87d6d 100644 --- a/crates/native-cpu-expert/examples/kernel_ab/main.rs +++ b/crates/native-cpu-expert/examples/kernel_ab/main.rs @@ -1,35 +1,44 @@ #![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. +// 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. +//! 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 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-.rust-.out` and one -//! COMPONENT_KERNEL record per case and tree to `R/records/` +//! 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-.rust-.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 +//! 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): +//! 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). +//! 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 @@ -51,15 +60,34 @@ use std::time::{Instant, SystemTime, UNIX_EPOCH}; thread_local! { static BUFFERS: Cell = const { Cell::new(0) }; } +/// `time` and `alternate` take flags only (the command line of `kab time`). +fn flag_command(cmd: &str, rest: &[String]) -> ExitCode { + let result = if cmd == "time" { cmd_time(rest) } else { cmd_alternate(rest) }; + result.unwrap_or_else(|e| { + eprintln!("kernel_ab {cmd}: {e}"); + ExitCode::from(1) + }) +} + +/// `verify D`: exit 0 when the directory is accepted, 2 when it is incomplete, 1 when it is refused. +fn verify_command(dir: &Path) -> Result { + 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 })) + } + } +} + fn main() -> ExitCode { let args: Vec = 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 + // 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) - }); + return flag_command(cmd, &args[1..]); } let (Some(cmd), Some(dir)) = (args.first(), args.get(1)) else { return usage() }; let dir = Path::new(dir); @@ -71,16 +99,7 @@ fn main() -> ExitCode { } }; 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 })) - } - }, + "verify" => verify_command(dir), "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()), @@ -94,304 +113,76 @@ fn main() -> ExitCode { }) } -// ------------------------------------------------------------------------------------------------ tests +// -------------------------------------------------------------------------------------------- tests #[cfg(test)] mod tests; mod gate_up_row_fn; #[allow(unused_imports)] -use gate_up_row_fn::civil_from_days; -#[allow(unused_imports)] -use gate_up_row_fn::down_row; -#[allow(unused_imports)] -use gate_up_row_fn::gate_up_row; -#[allow(unused_imports)] -use gate_up_row_fn::is_hex; -#[allow(unused_imports)] -use gate_up_row_fn::is_utc; -#[allow(unused_imports)] -use gate_up_row_fn::le32; -#[allow(unused_imports)] -use gate_up_row_fn::now_utc; -#[allow(unused_imports)] -use gate_up_row_fn::sha_hex; -#[allow(unused_imports)] -use gate_up_row_fn::take_buffer; -#[allow(unused_imports)] -use gate_up_row_fn::utc_of; -#[allow(unused_imports)] -use gate_up_row_fn::valid_id; -#[allow(unused_imports)] -use gate_up_row_fn::words_le; +use gate_up_row_fn::{ + civil_from_days, down_row, gate_up_row, is_hex, is_utc, le32, now_utc, sha_hex, take_buffer, utc_of, valid_id, + words_le, +}; mod impl_parser; #[allow(unused_imports)] use impl_parser::parse_json; mod validate_in_header_fn; #[allow(unused_imports)] -use validate_in_header_fn::case_files; -#[allow(unused_imports)] -use validate_in_header_fn::fp16_finite; -#[allow(unused_imports)] -use validate_in_header_fn::parse_manifest; -#[allow(unused_imports)] -use validate_in_header_fn::validate_in_header; -#[allow(unused_imports)] -use validate_in_header_fn::validate_out_header; +use validate_in_header_fn::{case_files, fp16_finite, parse_manifest, validate_in_header, validate_out_header}; mod read_case_in_fn; #[allow(unused_imports)] -use read_case_in_fn::compare_bits; -#[allow(unused_imports)] -use read_case_in_fn::jstr; -#[allow(unused_imports)] -use read_case_in_fn::read_case_in; -#[allow(unused_imports)] -use read_case_in_fn::read_manifest; -#[allow(unused_imports)] -use read_case_in_fn::read_out; -#[allow(unused_imports)] -use read_case_in_fn::record_json; -#[allow(unused_imports)] -use read_case_in_fn::verify_dir; +use read_case_in_fn::{compare_bits, jstr, read_case_in, read_manifest, read_out, record_json, verify_dir}; mod write_out_fn; #[allow(unused_imports)] -use write_out_fn::cmd_run_tree; -#[allow(unused_imports)] -use write_out_fn::compute_case; -#[allow(unused_imports)] -use write_out_fn::cpu_model_of; -#[allow(unused_imports)] -use write_out_fn::family_of; -#[allow(unused_imports)] -use write_out_fn::host_os; -#[allow(unused_imports)] -use write_out_fn::parse_options; -#[allow(unused_imports)] -use write_out_fn::rustc_info; -#[allow(unused_imports)] -use write_out_fn::sibling_idle; -#[allow(unused_imports)] -use write_out_fn::write_out; +use write_out_fn::{ + cmd_run_tree, compute_case, cpu_model_of, family_of, host_os, parse_options, rustc_info, sibling_idle, write_out, +}; mod cmd_compare_fn; #[allow(unused_imports)] -use cmd_compare_fn::cmd_compare; -#[allow(unused_imports)] -use cmd_compare_fn::core_ghz; -#[allow(unused_imports)] -use cmd_compare_fn::jnum; -#[allow(unused_imports)] -use cmd_compare_fn::median_of; -#[allow(unused_imports)] -use cmd_compare_fn::mono_ns; -#[allow(unused_imports)] -use cmd_compare_fn::parse_cpu_list; -#[allow(unused_imports)] -use cmd_compare_fn::parse_size; -#[allow(unused_imports)] -use cmd_compare_fn::percentile_of; -#[allow(unused_imports)] -use cmd_compare_fn::read_text; +use cmd_compare_fn::{ + cmd_compare, core_ghz, jnum, median_of, mono_ns, parse_cpu_list, parse_size, percentile_of, read_text, +}; mod llc_of_cpu_fn; #[allow(unused_imports)] -use llc_of_cpu_fn::busy_fraction; -#[allow(unused_imports)] -use llc_of_cpu_fn::current_cpu; -#[allow(unused_imports)] -use llc_of_cpu_fn::is_managed_name; -#[allow(unused_imports)] -use llc_of_cpu_fn::json_env; -#[allow(unused_imports)] -use llc_of_cpu_fn::llc_of_cpu; -#[allow(unused_imports)] -use llc_of_cpu_fn::managed_env_now; -#[allow(unused_imports)] -use llc_of_cpu_fn::observed_threads; -#[allow(unused_imports)] -use llc_of_cpu_fn::parse_time_args; -#[allow(unused_imports)] -use llc_of_cpu_fn::proc_stat_cpu; -#[allow(unused_imports)] -use llc_of_cpu_fn::slice_json; -#[allow(unused_imports)] -use llc_of_cpu_fn::time_slice; +use llc_of_cpu_fn::{ + busy_fraction, current_cpu, is_managed_name, json_env, llc_of_cpu, managed_env_now, observed_threads, + parse_time_args, proc_stat_cpu, slice_json, time_slice, +}; mod run_regime_fn; #[allow(unused_imports)] -use run_regime_fn::f32_bits_sha; -#[allow(unused_imports)] -use run_regime_fn::run_regime; +use run_regime_fn::{f32_bits_sha, run_regime}; mod cmd_time_fn; #[allow(unused_imports)] use cmd_time_fn::cmd_time; mod impl_impl; #[allow(unused_imports)] -use impl_impl::cell_env; -#[allow(unused_imports)] -use impl_impl::inside_git_checkout; -#[allow(unused_imports)] -use impl_impl::make_schedule; -#[allow(unused_imports)] -use impl_impl::parse_regime; -#[allow(unused_imports)] -use impl_impl::parse_schedule; -#[allow(unused_imports)] -use impl_impl::procs_for; -#[allow(unused_imports)] -use impl_impl::run_cell; -#[allow(unused_imports)] -use impl_impl::schedule_text; -#[allow(unused_imports)] -use impl_impl::scrubbed_command; -#[allow(unused_imports)] -use impl_impl::splitmix; +use impl_impl::{ + cell_env, inside_git_checkout, make_schedule, parse_regime, parse_schedule, procs_for, run_cell, schedule_text, + scrubbed_command, splitmix, +}; mod describe_cpp_tree_fn; #[allow(unused_imports)] -use describe_cpp_tree_fn::aa_outcome; -#[allow(unused_imports)] -use describe_cpp_tree_fn::describe_cpp_tree; -#[allow(unused_imports)] -use describe_cpp_tree_fn::equality_block; -#[allow(unused_imports)] -use describe_cpp_tree_fn::parse_proc_json; -#[allow(unused_imports)] -use describe_cpp_tree_fn::side_stat; -#[allow(unused_imports)] -use describe_cpp_tree_fn::stat_json; -#[allow(unused_imports)] -use describe_cpp_tree_fn::tool_json; +use describe_cpp_tree_fn::{ + aa_outcome, describe_cpp_tree, equality_block, parse_proc_json, side_stat, stat_json, tool_json, +}; mod round_records_fn; #[allow(unused_imports)] -use round_records_fn::aa_equality_block; -#[allow(unused_imports)] -use round_records_fn::create_new_file; -#[allow(unused_imports)] -use round_records_fn::file_sha; -#[allow(unused_imports)] -use round_records_fn::ours_flags; -#[allow(unused_imports)] -use round_records_fn::parse_alt_args; -#[allow(unused_imports)] -use round_records_fn::round_records; +use round_records_fn::{aa_equality_block, create_new_file, file_sha, ours_flags, parse_alt_args, round_records}; mod cmd_alternate_fn; #[allow(unused_imports)] -use cmd_alternate_fn::cmd_alternate; -#[allow(unused_imports)] -use cmd_alternate_fn::usage; - +use cmd_alternate_fn::{cmd_alternate, usage}; mod in_magic_types; #[allow(unused_imports)] -use in_magic_types::ALIGN; -#[allow(unused_imports)] -use in_magic_types::CHAIN_STEP_CYCLES; -#[allow(unused_imports)] -use in_magic_types::CLOCK_METHOD; -#[allow(unused_imports)] -use in_magic_types::CLOCK_MOVED_FRACTION; -#[allow(unused_imports)] -use in_magic_types::CaseEntry; -#[allow(unused_imports)] -use in_magic_types::CaseIn; -#[allow(unused_imports)] -use in_magic_types::DEFAULT_SLICE_MS; -#[allow(unused_imports)] -use in_magic_types::DOWN; -#[allow(unused_imports)] -use in_magic_types::FF; -#[allow(unused_imports)] -use in_magic_types::FileTable; -#[allow(unused_imports)] -use in_magic_types::Flags; -#[allow(unused_imports)] -use in_magic_types::GATE_UP; -#[allow(unused_imports)] -use in_magic_types::H; -#[allow(unused_imports)] -use in_magic_types::IN_HEADER; -#[allow(unused_imports)] -use in_magic_types::IN_MAGIC; -#[allow(unused_imports)] -use in_magic_types::InHeader; -#[allow(unused_imports)] -use in_magic_types::Json; -#[allow(unused_imports)] -use in_magic_types::Llc; -#[allow(unused_imports)] -use in_magic_types::MAX_CASES; -#[allow(unused_imports)] -use in_magic_types::MAX_FILE_BYTES; -#[allow(unused_imports)] -use in_magic_types::MAX_MANIFEST_BYTES; -#[allow(unused_imports)] -use in_magic_types::MAX_ROWS; -#[allow(unused_imports)] -use in_magic_types::NOT_MEASURED; -#[allow(unused_imports)] -use in_magic_types::OUT_HEADER; -#[allow(unused_imports)] -use in_magic_types::OUT_MAGIC; -#[allow(unused_imports)] -use in_magic_types::Options; -#[allow(unused_imports)] -use in_magic_types::OutRef; -#[allow(unused_imports)] -use in_magic_types::Outcome; -#[allow(unused_imports)] -use in_magic_types::Parser; -#[allow(unused_imports)] -use in_magic_types::Provenance; -#[allow(unused_imports)] -use in_magic_types::RecordInput; -#[allow(unused_imports)] -use in_magic_types::Refusal; -#[allow(unused_imports)] -use in_magic_types::RegimeSel; -#[allow(unused_imports)] -use in_magic_types::SIBLING_BUSY_LIMIT; -#[allow(unused_imports)] -use in_magic_types::TOLERANCE_METRIC; -#[allow(unused_imports)] -use in_magic_types::TREES; -#[allow(unused_imports)] -use in_magic_types::Tolerance; -#[allow(unused_imports)] -use in_magic_types::Verified; +use in_magic_types::{ + ALIGN, CHAIN_STEP_CYCLES, CLOCK_METHOD, CLOCK_MOVED_FRACTION, CaseEntry, CaseIn, DEFAULT_SLICE_MS, DOWN, FF, + FileTable, Flags, GATE_UP, H, IN_HEADER, IN_MAGIC, InHeader, Json, Llc, MAX_CASES, MAX_FILE_BYTES, + MAX_MANIFEST_BYTES, MAX_ROWS, NOT_MEASURED, OUT_HEADER, OUT_MAGIC, Options, OutRef, Outcome, Parser, Provenance, + RecordInput, Refusal, RegimeSel, SIBLING_BUSY_LIMIT, TOLERANCE_METRIC, TREES, Tolerance, Verified, +}; mod time_args_types; #[allow(unused_imports)] -use time_args_types::ALT_FLAGS; -#[allow(unused_imports)] -use time_args_types::AltArgs; -#[allow(unused_imports)] -use time_args_types::Arena; -#[allow(unused_imports)] -use time_args_types::BatchCtx; -#[allow(unused_imports)] -use time_args_types::Expect; -#[allow(unused_imports)] -use time_args_types::Impl; -#[allow(unused_imports)] -use time_args_types::Kind; -#[allow(unused_imports)] -use time_args_types::Numbered; -#[allow(unused_imports)] -use time_args_types::Proc; -#[allow(unused_imports)] -use time_args_types::ProcOut; -#[allow(unused_imports)] -use time_args_types::RegimeRun; -#[allow(unused_imports)] -use time_args_types::RegimeSpec; -#[allow(unused_imports)] -use time_args_types::RegimeStat; -#[allow(unused_imports)] -use time_args_types::SCHEDULE_MAGIC; -#[allow(unused_imports)] -use time_args_types::SideStat; -#[allow(unused_imports)] -use time_args_types::Slice; -#[allow(unused_imports)] -use time_args_types::TIME_FLAGS; -#[allow(unused_imports)] -use time_args_types::TimeArgs; -#[allow(unused_imports)] -use time_args_types::Timed; -#[allow(unused_imports)] -use time_args_types::Tool; +use time_args_types::{ + ALT_FLAGS, AltArgs, Arena, BatchCtx, Expect, Impl, Kind, Numbered, Proc, ProcOut, RegimeRun, RegimeSpec, + RegimeStat, SCHEDULE_MAGIC, SideStat, Slice, TIME_FLAGS, TimeArgs, Timed, Tool, +}; diff --git a/crates/native-cpu-expert/examples/kernel_ab/read_case_in_fn.rs b/crates/native-cpu-expert/examples/kernel_ab/read_case_in_fn.rs index 78c03831..c49bac07 100644 --- a/crates/native-cpu-expert/examples/kernel_ab/read_case_in_fn.rs +++ b/crates/native-cpu-expert/examples/kernel_ab/read_case_in_fn.rs @@ -1,34 +1,51 @@ -//! Moved out of the parent module by STRA-338: fn read_case_in, fn read_out, fn read_manifest, fn verify_dir, impl Outcome, fn compare_bits .... +//! Moved out of the parent module by STRA-338: fn read_case_in, fn read_out, fn read_manifest, fn verify_dir, impl +//! Outcome, fn compare_bits .... #[allow(unused_imports)] use super::*; -/// 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. -pub(super) fn read_case_in(dir: &Path, c: &CaseEntry) -> Result { - let name = c.in_name.as_str(); +mod record; +pub(super) use record::record_json; + +/// Opens a data file and reads its length; a failure names `name`. +fn open_file(path: &Path, name: &str) -> Result<(File, u64), Refusal> { 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 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(); + Ok((f, len)) +} + +fn read_header(f: &mut File, name: &str) -> Result<[u8; N], Refusal> { + let mut hdr = [0u8; N]; + f.read_exact(&mut hdr).map_err(|e| Refusal::new(name, format!("cannot read the header: {e}")))?; + Ok(hdr) +} + +/// The whole file in one buffer: the already-read header `hdr` and the rest from `f`. +fn read_body(f: &mut File, hdr: &[u8], len: u64, name: &str) -> Result, Refusal> { + let r = |reason: String| Refusal::new(name, reason); + let mut blob = take_buffer(len as usize).map_err(r)?; + blob[..hdr.len()].copy_from_slice(hdr); + f.read_exact(&mut blob[hdr.len()..]).map_err(|e| r(format!("cannot read the body: {e}")))?; + Ok(blob) +} + +/// The length of a case input against the manifest's and against the limits. +fn check_in_len(len: u64, c: &CaseEntry) -> Result<(), Refusal> { + let r = |reason: String| Refusal::new(&c.in_name, reason); 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 }; + Ok(()) +} + +/// The FP16 block headers of the three weight tensors and every activation must be finite. +fn check_case_values(case: &CaseIn, name: &str) -> Result<(), Refusal> { + let r = |reason: String| Refusal::new(name, reason); + let header = case.header; 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) { @@ -38,9 +55,49 @@ pub(super) fn read_case_in(dir: &Path, c: &CaseEntry) -> Result 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(()) +} + +/// The header's types and rows are the manifest case's. +fn header_matches(header: &InHeader, c: &CaseEntry) -> bool { + header.gu == c.gu && header.down == c.down && header.rows == c.rows +} + +/// 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. +pub(super) fn read_case_in(dir: &Path, c: &CaseEntry) -> Result { + let name = c.in_name.as_str(); + let r = |reason: String| Refusal::new(name, reason); + let (mut f, len) = open_file(&dir.join(name), name)?; + check_in_len(len, c)?; + let hdr = read_header::(&mut f, name)?; + let header = validate_in_header(&hdr, len).map_err(r)?; + if !header_matches(&header, c) { + return Err(r("the header's types / rows differ from the manifest case".to_owned())); + } + let blob = read_body(&mut f, &hdr, len, name)?; + if sha_hex(&blob) != c.in_sha256 { + return Err(r("sha256 differs from the manifest".to_owned())); + } + let case = CaseIn { header, blob }; + check_case_values(&case, name)?; Ok(case) } +/// The length of an `.out` file against the manifest's (a C++ file only) and against the limits. +fn check_out_len(len: u64, expect: Option<(&str, u64)>, name: &str) -> Result<(), Refusal> { + let r = |reason: String| Refusal::new(name, reason); + 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}"))); + } + Ok(()) +} + /// Reads an `.out` file as f32 bit patterns. `expect` is the manifest's (sha256, bytes) for a C++ file; ours has none. pub(super) fn read_out( path: &Path, @@ -50,22 +107,11 @@ pub(super) fn read_out( expect: Option<(&str, u64)>, ) -> Result, 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}")))?; + let (mut f, len) = open_file(path, name)?; + check_out_len(len, expect, name)?; + let hdr = read_header::(&mut f, name)?; 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}")))?; + let blob = read_body(&mut f, &hdr, len, name)?; if let Some((sha, _)) = expect && sha_hex(&blob) != sha { @@ -78,8 +124,8 @@ pub(super) fn read_out( 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. +/// 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. pub(super) fn read_manifest(dir: &Path) -> Result<(Vec, Provenance, Vec, FileTable), Refusal> { let mpath = dir.join("manifest.json"); let mname = "manifest.json"; @@ -101,20 +147,20 @@ pub(super) fn read_manifest(dir: &Path) -> Result<(Vec, Provenance, Vec Result { - 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(); +/// The flat files table and the case entries must describe exactly the same files. +fn check_files_table(expected: &[(&str, &str, u64)], files: &FileTable) -> Result<(), Refusal> { 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())); + return Err(Refusal::new("manifest.json", "the flat files table and the case entries disagree".to_owned())); } - let names: BTreeSet<&str> = expected.iter().map(|e| e.0).collect(); + Ok(()) +} + +/// Every file in the directory is named by the manifest. +fn check_listing(dir: &Path, names: &BTreeSet<&str>) -> Result<(), Refusal> { + let mname = "manifest.json"; + let r = |reason: String| Refusal::new(mname, reason); 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}")))?; @@ -123,6 +169,18 @@ pub(super) fn verify_dir(dir: &Path) -> Result { return Err(Refusal::new(&n, "file is not in the manifest")); } } + Ok(()) +} + +/// The reader rule. Everything in the directory is checked before anything is used; any problem refuses the whole +/// directory. +pub(super) fn verify_dir(dir: &Path) -> Result { + let (mbytes, provenance, cases, files) = read_manifest(dir)?; + let mut expected: Vec<(&str, &str, u64)> = cases.iter().flat_map(case_files).collect(); + expected.sort_unstable(); + check_files_table(&expected, &files)?; + let names: BTreeSet<&str> = expected.iter().map(|e| e.0).collect(); + check_listing(dir, &names)?; let file_count = names.len() + 1; for c in &cases { read_case_in(dir, c)?; @@ -138,8 +196,8 @@ impl Outcome { } } -/// 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`). +/// 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`). pub(super) 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 { @@ -150,21 +208,7 @@ pub(super) fn compare_bits(ours: &[u32], reference: &[u32], tol: Option<&Toleran 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)); - } + tally(&mut o, (i, *a, *b), tol, scale); } if ours.len() != reference.len() { o.mismatches += ours.len().abs_diff(reference.len()); @@ -172,7 +216,26 @@ pub(super) fn compare_bits(ours: &[u32], reference: &[u32], tol: Option<&Toleran o } -// ------------------------------------------------------------------------------------------------ record (hand-written JSON) +/// Counts one compared value `(index, ours, reference)` into the outcome. +fn tally(o: &mut Outcome, (i, a, b): (usize, u32, u32), tol: Option<&Tolerance>, scale: f64) { + 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)); + } +} + +// ---------------------------------------------------------------------------------------- record (hand-written JSON) pub(super) fn jstr(s: &str) -> String { let mut o = String::with_capacity(s.len() + 2); @@ -191,52 +254,3 @@ pub(super) fn jstr(s: &str) -> String { o.push('"'); o } - -pub(super) 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, - ) -} diff --git a/crates/native-cpu-expert/examples/kernel_ab/read_case_in_fn/record.rs b/crates/native-cpu-expert/examples/kernel_ab/read_case_in_fn/record.rs new file mode 100644 index 00000000..1c4f1296 --- /dev/null +++ b/crates/native-cpu-expert/examples/kernel_ab/read_case_in_fn/record.rs @@ -0,0 +1,104 @@ +//! The COMPONENT_KERNEL record of one `compare` cell, written as hand-made JSON in five consecutive sections. + +#[allow(unused_imports)] +use super::*; + +pub(crate) fn record_json(r: &RecordInput) -> String { + let (gu, down) = type_names(r.case); + [head(r, gu, down), toolchain(r), identity(r), timing_rows(r, gu, down), equality(r)].concat() +} + +/// The names of the gate/up and the down format of a case ("?" for an id outside the KAB1 list). +fn type_names(c: &CaseEntry) -> (&'static str, &'static str) { + (gate_up_row(c.gu).map_or("?", |x| x.4), down_row(c.down).map_or("?", |x| x.4)) +} + +/// Schema header, record id, timestamps, machine and the kernel description. +fn head(r: &RecordInput, gu: &str, down: &str) -> String { + 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(&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})", + r.case.rows + )), + ) +} + +/// Our toolchain and the reference one. +fn toolchain(r: &RecordInput) -> String { + let p = &r.verified.provenance; + format!( + " \"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", + 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), + ) +} + +/// Case, hashes, tree, regime, pin and the upstream commit. +fn identity(r: &RecordInput) -> String { + let (c, p) = (r.case, &r.verified.provenance); + format!( + " \"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", + 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), + ) +} + +/// The placeholder clock calibration, the placeholder timing row and the placeholder A/A noise floor. +fn timing_rows(r: &RecordInput, gu: &str, down: &str) -> String { + let tiny = format!("{:e}", f64::from_bits(1)); + format!( + " \"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", + nm = jstr(NOT_MEASURED), + rowtype = jstr(&format!("{gu}+{down} r{} {NOT_MEASURED}", r.case.rows)), + ) +} + +/// The equality verdict, with the tolerance when the case declares one. +fn equality(r: &RecordInput) -> String { + 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) + ) + }); + format!( + " \"equality\": {{\n \"mode\": \"{mode}\",\n \"verdict\": \"{verdict}\",\n \"compared_values\": \ + {compared},\n \"mismatches\": {mism}{tolerance}\n }}\n}}\n", + verdict = if r.outcome.equal() { "EQUAL" } else { "NOT_EQUAL" }, + compared = r.outcome.compared, + mism = r.outcome.mismatches, + ) +} diff --git a/crates/native-cpu-expert/examples/kernel_ab/round_records_fn.rs b/crates/native-cpu-expert/examples/kernel_ab/round_records_fn.rs index 5839b0a0..88d74d96 100644 --- a/crates/native-cpu-expert/examples/kernel_ab/round_records_fn.rs +++ b/crates/native-cpu-expert/examples/kernel_ab/round_records_fn.rs @@ -1,161 +1,40 @@ -//! Moved out of the parent module by STRA-338: fn round_records, fn aa_equality_block, fn parse_alt_args, fn create_new_file, fn file_sha, fn ours_flags. +//! Moved out of the parent module by STRA-338: fn round_records, fn aa_equality_block, fn parse_alt_args, fn +//! create_new_file, fn file_sha, fn ours_flags. #[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, 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) -} +mod records; +pub(super) use records::round_records; pub(super) fn aa_equality_block(o: &Outcome) -> String { format!( - "{{\n \"mode\": \"bitwise\",\n \"verdict\": \"{}\",\n \"compared_values\": {},\n \"mismatches\": {}\n }}", + "{{\n \"mode\": \"bitwise\",\n \"verdict\": \"{}\",\n \"compared_values\": {},\n \"mismatches\": \ + {}\n }}", if o.equal() { "EQUAL" } else { "NOT_EQUAL" }, o.compared, o.mismatches ) } -pub(super) fn parse_alt_args(args: &[String]) -> Result { - let f = Flags::parse(args, &ALT_FLAGS)?; +/// The counts of the `alternate` command line, range checked: rounds, batch, the case id and the slices per regime. +struct AltCounts { + rounds: u32, + batch: u32, + case: String, + slices: usize, +} + +fn alt_rounds_batch(f: &Flags) -> Result<(u32, u32), String> { let rounds = f.number::("rounds")?.ok_or("--rounds is required")?; let batch = f.number::("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()); } + Ok((rounds, batch)) +} + +fn alt_case_slices(f: &Flags) -> Result<(String, usize), String> { let case = f.req("case")?.to_owned(); if !valid_id(&case) { return Err(format!("--case {case:?} is not a plain identifier")); @@ -164,16 +43,28 @@ pub(super) fn parse_alt_args(args: &[String]) -> Result { if !(1..=100_000).contains(&slices) { return Err("--slices must be 1..100000".to_owned()); } + Ok((case, slices)) +} + +fn alt_counts(f: &Flags) -> Result { + let (rounds, batch) = alt_rounds_batch(f)?; + let (case, slices) = alt_case_slices(f)?; + Ok(AltCounts { rounds, batch, case, slices }) +} + +pub(super) fn parse_alt_args(args: &[String]) -> Result { + let f = Flags::parse(args, &ALT_FLAGS)?; + let c = alt_counts(&f)?; Ok(AltArgs { dir: PathBuf::from(f.req("run-dir")?), - case, - rounds, - batch, + case: c.case, + rounds: c.rounds, + batch: c.batch, pin: f.number::("pin")?.ok_or("--pin is required")?, schedule: PathBuf::from(f.req("schedule")?), seed: f.number::("seed")?.unwrap_or(1), out: f.get("out").map(PathBuf::from), - slices, + slices: c.slices, slice_ms: f.number::("slice-ms")?, llc_bytes: f.number::("llc-bytes")?, machine_role: f.get("machine-role").map(str::to_owned), diff --git a/crates/native-cpu-expert/examples/kernel_ab/round_records_fn/records.rs b/crates/native-cpu-expert/examples/kernel_ab/round_records_fn/records.rs new file mode 100644 index 00000000..9969c692 --- /dev/null +++ b/crates/native-cpu-expert/examples/kernel_ab/round_records_fn/records.rs @@ -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, 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, 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" + ) + } +} diff --git a/crates/native-cpu-expert/examples/kernel_ab/run_regime_fn.rs b/crates/native-cpu-expert/examples/kernel_ab/run_regime_fn.rs index 58f7254a..bca34167 100644 --- a/crates/native-cpu-expert/examples/kernel_ab/run_regime_fn.rs +++ b/crates/native-cpu-expert/examples/kernel_ab/run_regime_fn.rs @@ -3,19 +3,71 @@ #[allow(unused_imports)] use super::*; -pub(super) fn run_regime(t: &mut Timed, spec: &RegimeSpec) -> Result { - 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 +/// The warm-up (not recorded): tables and buffers, and for STREAMED one full pass over the copies so every page is +/// resident. +fn warm_up(t: &mut Timed, spec: &RegimeSpec, next: &mut usize) -> Result<(), String> { for _ in 0..3 { - t.call(spec.copies[next % spec.copies.len()])?; - next += 1; + 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; + t.call(spec.copies[*next % spec.copies.len()])?; + *next += 1; } } + Ok(()) +} + +/// The statistics object of a regime up to its medians (no trailing comma). +fn regime_head(spec: &RegimeSpec, counts: (usize, usize), migrated: Option, meds: (String, String)) -> String { + 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\": {}", + 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, + counts.0, + counts.1, + spec.selfcheck, + migrated.map_or("null".to_owned(), |m| m.to_string()), + meds.0, + meds.1 + ) +} + +/// The JSON of a regime: the statistics and the kept and the dropped slices. +fn regime_json( + spec: &RegimeSpec, + kept: &[(usize, Slice)], + dropped: &[(usize, Slice)], + migrated: Option, +) -> String { + let ns: Vec = kept.iter().map(|k| k.1.ns_per_call).collect(); + let cyc: Vec = 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::>().join(",\n "); + let head = regime_head(spec, (kept.len(), dropped.len()), migrated, (med(&ns, 3), med(&cyc, 1))); + format!( + "{head},\n \"slices\": [\n {}],\n \"dropped\": [\n {}]}}", + list(kept), + list(dropped) + ) +} + +pub(super) fn run_regime(t: &mut Timed, spec: &RegimeSpec) -> Result { + let mut next = 0usize; + warm_up(t, spec, &mut next)?; let (mut kept, mut dropped): (Numbered, Numbered) = (Vec::new(), Vec::new()); let mut migrated: Option = cfg!(target_os = "linux").then_some(0); for i in 0..spec.slices { @@ -28,32 +80,7 @@ pub(super) fn run_regime(t: &mut Timed, spec: &RegimeSpec) -> Result = kept.iter().map(|k| k.1.ns_per_call).collect(); - let cyc: Vec = 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::>().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) - ); + let json = regime_json(spec, &kept, &dropped, migrated); Ok(RegimeRun { json, kept: kept.len(), ok: !kept.is_empty() && migrated.is_none_or(|m| m == 0) }) } diff --git a/crates/native-cpu-expert/examples/kernel_ab/time_args_types.rs b/crates/native-cpu-expert/examples/kernel_ab/time_args_types.rs index d01283d1..a3363a7a 100644 --- a/crates/native-cpu-expert/examples/kernel_ab/time_args_types.rs +++ b/crates/native-cpu-expert/examples/kernel_ab/time_args_types.rs @@ -65,7 +65,7 @@ pub(super) struct RegimeSpec<'a> { pub(super) selfcheck: bool, } -// ------------------------------------------------------------------------------------------------ alternate: cells, environment, schedule +// ----------------------------------------------------------------- alternate: cells, environment, schedule #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)] pub(super) enum Impl { @@ -83,7 +83,7 @@ pub(super) struct Proc { pub(super) const SCHEDULE_MAGIC: &str = "# KAB1-alt schedule v1"; -// ------------------------------------------------------------------------------------------------ alternate: reading a process's JSON +// --------------------------------------------------------------------- alternate: reading a process's JSON #[derive(Debug, Clone)] pub(super) struct RegimeStat { @@ -122,8 +122,9 @@ pub(super) struct Expect<'a> { pub(super) pin: usize, } -// ------------------------------------------------------------------------------------------------ alternate: round records +// -------------------------------------------------------------------------------- alternate: round records +#[derive(Clone)] pub(super) struct Tool { pub(super) compiler: String, pub(super) version: String, @@ -159,7 +160,7 @@ pub(super) struct BatchCtx<'a> { pub(super) equality: &'a BTreeMap<&'static str, Outcome>, } -// ------------------------------------------------------------------------------------------------ alternate: the runner +// ----------------------------------------------------------------------------------- alternate: the runner pub(super) const ALT_FLAGS: [&str; 13] = [ "run-dir", diff --git a/crates/native-cpu-expert/examples/kernel_ab/validate_in_header_fn.rs b/crates/native-cpu-expert/examples/kernel_ab/validate_in_header_fn.rs index 3f67a3d9..d69acdd1 100644 --- a/crates/native-cpu-expert/examples/kernel_ab/validate_in_header_fn.rs +++ b/crates/native-cpu-expert/examples/kernel_ab/validate_in_header_fn.rs @@ -1,23 +1,22 @@ -//! Moved out of the parent module by STRA-338: fn validate_in_header, fn validate_out_header, fn fp16_finite, fn parse_manifest, fn case_files, impl CaseIn. +//! Moved out of the parent module by STRA-338: fn validate_in_header, fn validate_out_header, fn fp16_finite, fn +//! parse_manifest, fn case_files, impl CaseIn. #[allow(unused_imports)] use super::*; -/// Pure: decides from 64 header bytes and the file length, allocates nothing. -pub(super) fn validate_in_header(h: &[u8; IN_HEADER], file_len: u64) -> Result { - if le32(h, 0) != IN_MAGIC { - return Err(format!("wrong magic 0x{:08x}, expected 0x{IN_MAGIC:08x}", le32(h, 0))); +/// The magic number and the version (1) that open both KAB1 headers. +fn check_magic_version(h: &[u8], magic: u32) -> Result<(), String> { + if le32(h, 0) != magic { + return Err(format!("wrong magic 0x{:08x}, expected 0x{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")); - }; + Ok(()) +} + +/// Row count and the fixed model dimensions of an input header. +fn check_rows_dims(h: &[u8; IN_HEADER]) -> Result { let rows = le32(h, 16) as usize; if !(1..=MAX_ROWS).contains(&rows) { return Err(format!("rows {rows} outside 1..={MAX_ROWS}")); @@ -25,14 +24,34 @@ pub(super) fn validate_in_header(h: &[u8; IN_HEADER], file_len: u64) -> Result Result<(u64, u64, u64), String> { 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}" )); } + Ok((g, u, d)) +} + +/// Pure: decides from 64 header bytes and the file length, allocates nothing. +pub(super) fn validate_in_header(h: &[u8; IN_HEADER], file_len: u64) -> Result { + check_magic_version(h, IN_MAGIC)?; + 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 = check_rows_dims(h)?; + let gsize = (H / gq * gb * FF) as u64; + let dsize = (FF / dq * db * H) as u64; + let (g, u, d) = check_byte_counts(h, gsize, dsize)?; if h[40..].iter().any(|b| *b != 0) { return Err("header padding is not zero".to_owned()); } @@ -45,12 +64,7 @@ pub(super) fn validate_in_header(h: &[u8; IN_HEADER], file_len: u64) -> Result 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))); - } + check_magic_version(h, OUT_MAGIC)?; 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))); } @@ -73,6 +87,15 @@ pub(super) fn parse_manifest(m: &Json) -> Result<(Provenance, Vec, Fi if m.str("format")? != "KAB1" || m.uint("version")? != 1 { return Err("format is not KAB1 version 1".to_owned()); } + let (provenance, built) = parse_provenance(m)?; + let cases = parse_cases(m, built)?; + let files = parse_files(m)?; + check_case_hashes(&cases)?; + Ok((provenance, cases, files)) +} + +/// The provenance of the reference run and its build time (`built_at_utc`). +fn parse_provenance(m: &Json) -> Result<(Provenance, &str), String> { let p = m.req("provenance")?; let flags = p.req("flags")?; let commit = p.str("engine_strata_pin")?; @@ -87,7 +110,17 @@ pub(super) fn parse_manifest(m: &Json) -> Result<(Provenance, Vec, Fi Some(Json::Bool(b)) => Some(*b), _ => None, }; - let provenance = Provenance { + Ok((provenance_of(m, (p, flags), commit, avx512_ok)?, built)) +} + +/// The provenance record from the manifest `m`, its `provenance` object and the `flags` object `(p, flags)`. +fn provenance_of( + m: &Json, + (p, flags): (&Json, &Json), + commit: &str, + avx512_ok: Option, +) -> Result { + Ok(Provenance { run_id: m.str("run_id")?.to_owned(), engine_strata_pin: commit.to_owned(), compiler_id: p.str("compiler_id")?.to_owned(), @@ -99,83 +132,96 @@ pub(super) fn parse_manifest(m: &Json) -> Result<(Provenance, Vec, Fi flags.str("ggml_cpu_arch_flags")? ), avx512_ok, - }; + }) +} + +fn parse_cases(m: &Json, built: &str) -> Result, String> { 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")); + cases_json.iter().map(|c| parse_case(c, built)).collect() +} + +fn parse_case(c: &Json, built: &str) -> Result { + let (id, rows, in_name) = case_identity(c)?; + let outs = parse_outs(c, &id)?; + let tolerance = parse_tolerance(c, &id, built)?; + 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; + Ok(CaseEntry { id, gu, down, rows, in_name, in_sha256, in_bytes: c.uint("in_bytes")?, outs, tolerance }) +} + +/// (id, rows, input file name) of a manifest case; the id must be plain and the file name derived from it. +fn case_identity(c: &Json) -> Result<(String, usize, String), String> { + 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")?)); + } + Ok((id, rows, in_name)) +} + +/// The reference `.out` files of a case, one per tree. +fn parse_outs(c: &Json, id: &str) -> Result, String> { + 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)?)); } - 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::().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, + outs.push(OutRef { + tree, + name, + sha256: c.str(&format!("{key}_sha256"))?.to_owned(), + bytes: c.uint(&format!("{key}_bytes"))?, }); } + Ok(outs) +} + +/// The tolerance of a case: `bitwise` needs a null, `tolerance` an object. +fn parse_tolerance(c: &Json, id: &str, built: &str) -> Result, String> { + match (c.str("equality")?, c.req("tolerance")?) { + ("bitwise", Json::Null) => Ok(None), + ("tolerance", t @ Json::Obj(_)) => tolerance_object(t, id, built).map(Some), + (other, _) => Err(format!( + "case {id}: equality {other:?} and tolerance disagree (bitwise needs null, tolerance an object)" + )), + } +} + +fn tolerance_object(t: &Json, id: &str, built: &str) -> Result { + if t.str("metric")? != TOLERANCE_METRIC { + return Err(format!("case {id}: tolerance metric {:?} is not {TOLERANCE_METRIC}", t.str("metric")?)); + } + let value = tolerance_value(t, id)?; + 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}")); + } + Ok(Tolerance { value, basis, basis_written_utc: written }) +} + +fn tolerance_value(t: &Json, id: &str) -> Result { + match t.req("value")? { + Json::Num(n) => n.parse::().ok().filter(|v| v.is_finite() && *v > 0.0), + _ => None, + } + .ok_or_else(|| format!("case {id}: tolerance.value is not a positive number")) +} + +fn parse_files(m: &Json) -> Result { 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 { @@ -185,8 +231,13 @@ pub(super) fn parse_manifest(m: &Json) -> Result<(Provenance, Vec, Fi } files.push((name.clone(), sha.to_owned(), v.uint("bytes")?)); } + Ok(files) +} + +/// Case ids are unique and every sha256 of a case is 64 lowercase hex digits. +fn check_case_hashes(cases: &[CaseEntry]) -> Result<(), String> { let mut seen = BTreeSet::new(); - for c in &cases { + for c in cases { if !seen.insert(c.id.clone()) { return Err(format!("case id {} appears twice", c.id)); } @@ -196,7 +247,7 @@ pub(super) fn parse_manifest(m: &Json) -> Result<(Provenance, Vec, Fi } } } - Ok((provenance, cases, files)) + Ok(()) } pub(super) fn case_files(c: &CaseEntry) -> Vec<(&str, &str, u64)> { diff --git a/crates/native-cpu-expert/examples/kernel_ab/write_out_fn.rs b/crates/native-cpu-expert/examples/kernel_ab/write_out_fn.rs index 945b2681..353f6c25 100644 --- a/crates/native-cpu-expert/examples/kernel_ab/write_out_fn.rs +++ b/crates/native-cpu-expert/examples/kernel_ab/write_out_fn.rs @@ -1,9 +1,10 @@ -//! Moved out of the parent module by STRA-338: fn write_out, fn compute_case, fn family_of, fn cmd_run_tree, fn sibling_idle, fn rustc_info .... +//! Moved out of the parent module by STRA-338: fn write_out, fn compute_case, fn family_of, fn cmd_run_tree, fn +//! sibling_idle, fn rustc_info .... #[allow(unused_imports)] use super::*; -// ------------------------------------------------------------------------------------------------ run-tree (one fresh process) +// ---------------------------------------------------------------------------- run-tree (one fresh process) pub(super) 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; @@ -17,8 +18,8 @@ pub(super) fn write_out(path: &Path, rows: usize, tree: &str, values: &[f32]) -> 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). +/// 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). pub(super) fn compute_case(pool: &mut DirectCpuPool, case: &CaseIn) -> Result, 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); @@ -49,6 +50,41 @@ pub(super) fn family_of(report: &[String]) -> Option<&'static str> { .map(|l| if l.starts_with("cpu: process kernel family AVX-512") { "avx512" } else { "avx2" }) } +/// Pins the calling thread; a refused pin only warns (the run goes on unpinned). +fn pin_or_warn(pin: usize) { + 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"); + } +} + +/// Prints the kernel report of this process (one `REPORT` line each) and returns it. +fn print_kernel_report() -> Vec { + let report = cpu_kernel_report(); + for line in &report { + println!("REPORT {line}"); + } + report +} + +/// Our output of every selected case of the run directory, written below `target = (tree, out)`; returns the count. +fn run_tree_cases( + verified: &Verified, + pool: &mut DirectCpuPool, + target: (&str, &Path), + only_case: Option<&str>, +) -> Result { + let (tree, out) = target; + 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(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; + } + Ok(done) +} + pub(super) fn cmd_run_tree( dir: &Path, tree: &str, @@ -57,14 +93,8 @@ pub(super) fn cmd_run_tree( only_case: Option<&str>, ) -> Result { 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}"); - } + pin_or_warn(pin); + let report = print_kernel_report(); 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}"); @@ -72,13 +102,7 @@ pub(super) fn cmd_run_tree( } 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; - } + let done = run_tree_cases(&verified, &mut pool, (tree, out), only_case)?; if done == 0 { return Err(format!("case {} is not in the manifest", only_case.unwrap_or("?"))); } @@ -88,44 +112,57 @@ pub(super) fn cmd_run_tree( // ------------------------------------------------------------------------------------------------ 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). -pub(super) 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; - }; +/// The logical CPUs that share a core with `cpu` (from sysfs); None when the list cannot be read or parsed. +fn smt_siblings(cpu: usize) -> Option> { + let list = fs::read_to_string(format!("/sys/devices/system/cpu/cpu{cpu}/topology/thread_siblings_list")).ok()?; 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::(), b.trim().parse::()) else { return false }; + let (Ok(a), Ok(b)) = (a.trim().parse::(), b.trim().parse::()) else { return None }; 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 = 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(siblings) +} + +/// (total, idle) jiffies of one logical CPU from /proc/stat. +fn cpu_jiffies(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 = 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)) +} + +/// Below 5 percent busy between two samples; a missing sample or no elapsed time is not idle. +fn mostly_idle(before: Option<(u64, u64)>, after: Option<(u64, u64)>) -> bool { + match (before, after) { (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, - }) + } +} + +/// Linux: is the SMT sibling of `cpu` idle (below 5 percent busy over 200 ms)? No sibling counts as idle. Elsewhere: +/// false (unknown). +pub(super) fn sibling_idle(cpu: usize) -> bool { + if !cfg!(target_os = "linux") { + return false; + } + let Some(siblings) = smt_siblings(cpu) else { return false }; + if siblings.is_empty() { + return true; + } + let before: Vec<_> = siblings.iter().map(|s| cpu_jiffies(*s)).collect(); + std::thread::sleep(std::time::Duration::from_millis(200)); + siblings.iter().zip(before).all(|(s, b)| mostly_idle(b, cpu_jiffies(*s))) } pub(super) 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) + // $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]; @@ -174,19 +211,37 @@ pub(super) fn parse_options(args: &[String]) -> Result { }; 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}")), - } + apply_option(&mut o, a.as_str(), &mut it)?; } if let Some(bad) = o.trees.iter().find(|t| !TREES.contains(&t.as_str())) { return Err(format!("unknown tree {bad} (avx512 | avx2)")); } Ok(o) } + +/// The value after an option flag. +fn take_value(it: &mut std::slice::Iter<'_, String>, what: &str) -> Result { + it.next().cloned().ok_or_else(|| format!("{what} needs a value")) +} + +fn apply_option(o: &mut Options, flag: &str, it: &mut std::slice::Iter<'_, String>) -> Result<(), String> { + match flag { + "--out" => o.out = Some(PathBuf::from(take_value(it, "--out")?)), + "--pin" => { + o.pin = take_value(it, "--pin")?.parse().map_err(|_| "--pin takes a logical CPU number".to_owned())? + } + "--machine-role" => o.machine_role = Some(take_value(it, "--machine-role")?), + _ => return apply_tree_option(o, flag, it), + } + Ok(()) +} + +fn apply_tree_option(o: &mut Options, flag: &str, it: &mut std::slice::Iter<'_, String>) -> Result<(), String> { + match flag { + "--trees" => o.trees = take_value(it, "--trees")?.split(',').map(str::to_owned).collect(), + "--tree" => o.tree = Some(take_value(it, "--tree")?), + "--case" => o.case = Some(take_value(it, "--case")?), + other => return Err(format!("unknown option {other}")), + } + Ok(()) +} diff --git a/crates/native-cpu-expert/tests/borrowed_group_parity.rs b/crates/native-cpu-expert/tests/borrowed_group_parity.rs index 8b8c4a48..98aade84 100644 --- a/crates/native-cpu-expert/tests/borrowed_group_parity.rs +++ b/crates/native-cpu-expert/tests/borrowed_group_parity.rs @@ -8,7 +8,6 @@ use leleka_native_cpu_expert::{ BorrowedExpert, BorrowedGroup, CpuPool, DirectCpuPool, DownFormat, GateUpFormat, PreparedJob, }; -use std::time::Instant; const H: usize = 2560; const FF: usize = 640; @@ -110,63 +109,78 @@ fn plan(ids: &[usize], include: &[bool]) -> Vec<(usize, Vec<(usize, usize)>)> { jobs } -/// The previous serve path: copy every role into owned boxes, build owned inputs, run batches of 12 with -/// a join between them, scatter every expert's rows into the output. -fn owned_path( - pool: &mut CpuPool, +/// One planned expert: its index in the bank and the `(row, slot)` pairs it serves, in ascending order. +type Job = (usize, Vec<(usize, usize)>); + +/// The inputs both group paths run on. +#[derive(Clone, Copy)] +struct Work<'a> { gu: GateUpFormat, down: DownFormat, - bank: &[Expert], - tokens: &[f32], - jobs: &[(usize, Vec<(usize, usize)>)], - out: &mut [f32], -) { - for batch in jobs.chunks(OLD_BATCH) { - let mut prepared = Vec::with_capacity(batch.len()); - for (e, pairs) in batch { - let x = &bank[*e]; - let mut input = Vec::with_capacity(pairs.len() * H); - for &(row, _) in pairs { - input.extend_from_slice(&tokens[row * H..(row + 1) * H]); - } - prepared.push( - PreparedJob::new( - gu, - down, - x.gate.clone().into_boxed_slice(), - x.up.clone().into_boxed_slice(), - x.down.clone().into_boxed_slice(), - input.into_boxed_slice(), - pairs.len(), - ) - .expect("owned job"), - ); - } + bank: &'a [Expert], + tokens: &'a [f32], + jobs: &'a [Job], +} + +/// The tokens of the rows an expert serves, one after the other. +fn gather_input(tokens: &[f32], pairs: &[(usize, usize)]) -> Vec { + let mut input = Vec::with_capacity(pairs.len() * H); + for &(row, _) in pairs { + input.extend_from_slice(&tokens[row * H..(row + 1) * H]); + } + input +} + +/// Writes an expert's `values` (one `H` row per pair) into the `(row, slot)` cells of `out`. +fn scatter_rows(values: &[f32], pairs: &[(usize, usize)], out: &mut [f32]) { + for (i, &(row, slot)) in pairs.iter().enumerate() { + let at = (row * TOP_K + slot) * H; + out[at..at + H].copy_from_slice(&values[i * H..(i + 1) * H]); + } +} + +/// Copies every role into owned boxes and builds the owned input of one expert. +fn prepare_owned(w: &Work, e: usize, pairs: &[(usize, usize)]) -> PreparedJob { + let x = &w.bank[e]; + let input = gather_input(w.tokens, pairs); + PreparedJob::new( + w.gu, + w.down, + x.gate.clone().into_boxed_slice(), + x.up.clone().into_boxed_slice(), + x.down.clone().into_boxed_slice(), + input.into_boxed_slice(), + pairs.len(), + ) + .expect("owned job") +} + +type Prepare = fn(&Work, usize, &[(usize, usize)]) -> PreparedJob; + +/// Runs batches of 12 with a join between them and scatters every expert's rows into the output. +fn run_owned(pool: &mut CpuPool, w: &Work, out: &mut [f32], prepare: Prepare) { + for batch in w.jobs.chunks(OLD_BATCH) { + let prepared: Vec = batch.iter().map(|(e, pairs)| prepare(w, *e, pairs)).collect(); let done = pool.start(prepared, 48 << 20).expect("start").join().expect("join"); for (job, (_, pairs)) in done.into_iter().zip(batch) { - let values = job.into_values(); - for (i, &(row, slot)) in pairs.iter().enumerate() { - let at = (row * TOP_K + slot) * H; - out[at..at + H].copy_from_slice(&values[i * H..(i + 1) * H]); - } + scatter_rows(&job.into_values(), pairs, out); } } } -fn borrowed_path( - pool: &mut DirectCpuPool, - gu: GateUpFormat, - down: DownFormat, - bank: &[Expert], - tokens: &[f32], - jobs: &[(usize, Vec<(usize, usize)>)], - out: &mut [f32], -) { - let experts: Vec> = jobs +/// The previous serve path: copy every role into owned boxes, build owned inputs, run batches of 12 with +/// a join between them, scatter every expert's rows into the output. +fn owned_path(pool: &mut CpuPool, w: &Work, out: &mut [f32]) { + run_owned(pool, w, out, prepare_owned); +} + +fn borrowed_path(pool: &mut DirectCpuPool, w: &Work, out: &mut [f32]) { + let experts: Vec> = w + .jobs .iter() - .map(|(e, pairs)| BorrowedExpert { gate: &bank[*e].gate, up: &bank[*e].up, down: &bank[*e].down, pairs }) + .map(|(e, pairs)| BorrowedExpert { gate: &w.bank[*e].gate, up: &w.bank[*e].up, down: &w.bank[*e].down, pairs }) .collect(); - pool.compute_group(gu, down, &BorrowedGroup { tokens, experts: &experts, stride: TOP_K }, out) + pool.compute_group(w.gu, w.down, &BorrowedGroup { tokens: w.tokens, experts: &experts, stride: TOP_K }, out) .expect("borrowed group"); } @@ -183,151 +197,188 @@ const PAIRS: [(GateUpFormat, DownFormat); 10] = [ (GateUpFormat::Q2_0, DownFormat::Q2_0), ]; +/// The two pools the parity test runs the same groups through. +struct Pools { + owned: CpuPool, + direct: DirectCpuPool, +} + +/// One routed group of the parity test: the formats, the bank and the shape of the routing. +struct Spec<'a> { + gu: GateUpFormat, + down: DownFormat, + bank: &'a [Expert], + rows: usize, + share: usize, +} + +/// The file-mapped source's prefetch phase reads only: the group computes the same bits. +fn prefetch_group(direct: &mut DirectCpuPool, w: &Work) { + let refs: Vec> = w + .jobs + .iter() + .map(|(e, pairs)| BorrowedExpert { gate: &w.bank[*e].gate, up: &w.bank[*e].up, down: &w.bank[*e].down, pairs }) + .collect(); + direct.prefetch(w.gu, w.down, &refs).expect("prefetch"); +} + +fn assert_identical(a: &[f32], b: &[f32], s: &Spec) { + let (gu, down, rows, share) = (s.gu, s.down, s.rows, s.share); + let differing = a.iter().zip(b).filter(|(x, y)| x.to_bits() != y.to_bits()).count(); + assert_eq!(differing, 0, "{gu:?} x {down:?} rows={rows} share={share}: {differing} floats differ"); +} + +/// Prints the digest of every output bit and checks that only the planned rows were written, all finite. +fn check_written(b: &[f32], jobs: &[Job], s: &Spec) { + let (gu, down, rows, share) = (s.gu, s.down, s.rows, s.share); + // A digest of every output bit: compared across builds to prove a kernel change bit-exact. + let digest = + b.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, v| (h ^ u64::from(v.to_bits())).wrapping_mul(0x100_0000_01b3)); + eprintln!("DIGEST {gu:?} {down:?} rows={rows} share={share} {digest:016x}"); + let computed: usize = jobs.iter().map(|(_, p)| p.len()).sum(); + assert!( + b.iter().filter(|v| v.is_finite()).count() == computed * H, + "{gu:?} x {down:?}: only planned rows written, all finite" + ); +} + +/// Routes one group, runs it through both paths and compares every output bit; false when nothing was planned. +fn check_group(pools: &mut Pools, rng: &mut Rng, s: &Spec) -> bool { + let (ids, include) = route(rng, s.rows, s.bank.len(), s.share); + let jobs = plan(&ids, &include); + if jobs.is_empty() { + return false; + } + let tokens: Vec = (0..s.rows * H).map(|_| rng.unit()).collect(); + let w = Work { gu: s.gu, down: s.down, bank: s.bank, tokens: &tokens, jobs: &jobs }; + // different sentinels: rows the plan leaves out must stay untouched by both paths + let mut a = vec![f32::from_bits(0x7fc0_0001); s.rows * TOP_K * H]; + let mut b = vec![f32::from_bits(0x7fc0_0001); s.rows * TOP_K * H]; + owned_path(&mut pools.owned, &w, &mut a); + if s.share != 100 { + prefetch_group(&mut pools.direct, &w); + } + borrowed_path(&mut pools.direct, &w, &mut b); + assert_identical(&a, &b, s); + check_written(&b, &jobs, s); + true +} + +/// Every row count and CPU share of one format pair, on a small bank so rows share experts and batches of 12 are +/// crossed; returns the number of groups compared. +fn check_pair(pools: &mut Pools, rng: &mut Rng, (gu, down): (GateUpFormat, DownFormat)) -> usize { + let bank = bank(rng, gu, down, 40); + let mut groups = 0; + for rows in [1usize, 2, 3, 4, 6, 8] { + for share in [100usize, 50] { + groups += usize::from(check_group(pools, rng, &Spec { gu, down, bank: &bank, rows, share })); + } + } + groups +} + #[test] fn borrowed_group_is_bit_identical_to_the_owned_batches() { let workers = std::env::var("PARITY_WORKERS").ok().and_then(|v| v.parse().ok()).unwrap_or(4); - let mut owned = CpuPool::new(workers).expect("owned pool"); - let mut direct = DirectCpuPool::new(workers).expect("direct pool"); + let mut pools = Pools { + owned: CpuPool::new(workers).expect("owned pool"), + direct: DirectCpuPool::new(workers).expect("direct pool"), + }; let mut rng = Rng(0x9e37_79b9_7f4a_7c15); let mut groups = 0; - for (gu, down) in PAIRS { - // a small bank so rows share experts and batches of 12 are crossed - let bank = bank(&mut rng, gu, down, 40); - for rows in [1usize, 2, 3, 4, 6, 8] { - for share in [100usize, 50] { - let (ids, include) = route(&mut rng, rows, bank.len(), share); - let jobs = plan(&ids, &include); - if jobs.is_empty() { - continue; - } - let tokens: Vec = (0..rows * H).map(|_| rng.unit()).collect(); - // different sentinels: rows the plan leaves out must stay untouched by both paths - let mut a = vec![f32::from_bits(0x7fc0_0001); rows * TOP_K * H]; - let mut b = vec![f32::from_bits(0x7fc0_0001); rows * TOP_K * H]; - owned_path(&mut owned, gu, down, &bank, &tokens, &jobs, &mut a); - if share != 100 { - // the file-mapped source's prefetch phase reads only: the group computes the same bits - let refs: Vec> = jobs - .iter() - .map(|(e, pairs)| BorrowedExpert { - gate: &bank[*e].gate, - up: &bank[*e].up, - down: &bank[*e].down, - pairs, - }) - .collect(); - direct.prefetch(gu, down, &refs).expect("prefetch"); - } - borrowed_path(&mut direct, gu, down, &bank, &tokens, &jobs, &mut b); - let differing = a.iter().zip(&b).filter(|(x, y)| x.to_bits() != y.to_bits()).count(); - assert_eq!(differing, 0, "{gu:?} x {down:?} rows={rows} share={share}: {differing} floats differ"); - // A digest of every output bit: compared across builds to prove a kernel change bit-exact. - let digest = b - .iter() - .fold(0xcbf2_9ce4_8422_2325u64, |h, v| (h ^ u64::from(v.to_bits())).wrapping_mul(0x100_0000_01b3)); - eprintln!("DIGEST {gu:?} {down:?} rows={rows} share={share} {digest:016x}"); - let computed: usize = jobs.iter().map(|(_, p)| p.len()).sum(); - assert!( - b.iter().filter(|v| v.is_finite()).count() == computed * H, - "{gu:?} x {down:?}: only planned rows written, all finite" - ); - groups += 1; - } - } + for pair in PAIRS { + groups += check_pair(&mut pools, &mut rng, pair); } eprintln!("bit-identical groups: {groups}"); } -#[test] -fn borrowed_group_refuses_bad_shapes_without_touching_out() { - let mut direct = DirectCpuPool::new(2).expect("direct pool"); - let mut rng = Rng(7); - let (gu, down) = (GateUpFormat::Iq3S, DownFormat::Iq4Nl); - let bank = bank(&mut rng, gu, down, 2); - let tokens = vec![0.25f32; 2 * H]; - let mut out = vec![-3.0f32; 2 * TOP_K * H]; +/// The state a refused group must leave alone: the pool and the output. +struct Sink { + direct: DirectCpuPool, + out: Vec, +} + +const BAD_FORMATS: (GateUpFormat, DownFormat) = (GateUpFormat::Iq3S, DownFormat::Iq4Nl); + +fn expert<'a>(bank: &'a [Expert], i: usize, pairs: &'a [(usize, usize)]) -> BorrowedExpert<'a> { + BorrowedExpert { gate: &bank[i].gate, up: &bank[i].up, down: &bank[i].down, pairs } +} + +/// Runs a group of `experts` over `tokens` in format `gu` (the test's down format) and says whether it was refused. +fn refused(sink: &mut Sink, gu: GateUpFormat, tokens: &[f32], experts: &[BorrowedExpert]) -> bool { + let group = BorrowedGroup { tokens, experts, stride: TOP_K }; + sink.direct.compute_group(gu, BAD_FORMATS.1, &group, &mut sink.out).is_err() +} + +/// Duplicate pairs, rows out of range, slots beyond the stride and an empty group. +fn refuses_bad_pairs(sink: &mut Sink, bank: &[Expert], tokens: &[f32]) { let pairs_a = [(0usize, 1usize)]; let duplicate = [(0usize, 1usize)]; let out_of_rows = [(2usize, 0usize)]; let wide_slot = [(0usize, TOP_K)]; - let x = |pairs| BorrowedExpert { gate: &bank[0].gate, up: &bank[0].up, down: &bank[0].down, pairs }; - let y = |pairs| BorrowedExpert { gate: &bank[1].gate, up: &bank[1].up, down: &bank[1].down, pairs }; + let (x, y) = (|pairs| expert(bank, 0, pairs), |pairs| expert(bank, 1, pairs)); for experts in [vec![x(&pairs_a), y(&duplicate)], vec![x(&out_of_rows)], vec![x(&wide_slot)], vec![]] { - let group = BorrowedGroup { tokens: &tokens, experts: &experts, stride: TOP_K }; - assert!(direct.compute_group(gu, down, &group, &mut out).is_err()); + assert!(refused(sink, BAD_FORMATS.0, tokens, &experts)); } +} + +/// A gate matrix one byte short, and a group of another gate/up format than its bytes. +fn refuses_short_gate_and_wrong_format(sink: &mut Sink, bank: &[Expert], tokens: &[f32]) { + let pairs_a = [(0usize, 1usize)]; let short = BorrowedExpert { gate: &bank[0].gate[1..], up: &bank[0].up, down: &bank[0].down, pairs: &pairs_a }; - assert!( - direct - .compute_group(gu, down, &BorrowedGroup { tokens: &tokens, experts: &[short], stride: TOP_K }, &mut out) - .is_err() - ); - let wrong_format = [x(&pairs_a)]; - assert!( - direct - .compute_group( - GateUpFormat::Iq3Xxs, - down, - &BorrowedGroup { tokens: &tokens, experts: &wrong_format, stride: TOP_K }, - &mut out - ) - .is_err() - ); - let mut nan = tokens.clone(); + assert!(refused(sink, BAD_FORMATS.0, tokens, &[short])); + let wrong_format = [expert(bank, 0, &pairs_a)]; + assert!(refused(sink, GateUpFormat::Iq3Xxs, tokens, &wrong_format)); +} + +fn refuses_nan_tokens(sink: &mut Sink, bank: &[Expert], tokens: &[f32]) { + let pairs_a = [(0usize, 1usize)]; + let wrong_format = [expert(bank, 0, &pairs_a)]; + let mut nan = tokens.to_vec(); nan[5] = f32::NAN; - assert!( - direct - .compute_group(gu, down, &BorrowedGroup { tokens: &nan, experts: &wrong_format, stride: TOP_K }, &mut out) - .is_err() - ); - assert!(out.iter().all(|&v| v == -3.0), "a refused group writes nothing"); + assert!(refused(sink, BAD_FORMATS.0, &nan, &wrong_format)); +} + +fn serves_good_group(sink: &mut Sink, bank: &[Expert], tokens: &[f32]) { + let pairs_a = [(0usize, 1usize)]; + let good = [expert(bank, 0, &pairs_a)]; + let group = BorrowedGroup { tokens, experts: &good, stride: TOP_K }; + sink.direct.compute_group(BAD_FORMATS.0, BAD_FORMATS.1, &group, &mut sink.out).expect("good group"); + assert!(sink.out[H..2 * H].iter().all(|v| v.is_finite())); +} + +#[test] +fn borrowed_group_refuses_bad_shapes_without_touching_out() { + let (gu, down) = BAD_FORMATS; + let mut sink = Sink { direct: DirectCpuPool::new(2).expect("direct pool"), out: vec![-3.0f32; 2 * TOP_K * H] }; + let bank = bank(&mut Rng(7), gu, down, 2); + let tokens = vec![0.25f32; 2 * H]; + refuses_bad_pairs(&mut sink, &bank, &tokens); + refuses_short_gate_and_wrong_format(&mut sink, &bank, &tokens); + refuses_nan_tokens(&mut sink, &bank, &tokens); + assert!(sink.out.iter().all(|&v| v == -3.0), "a refused group writes nothing"); // and the pool still serves a good group afterwards - let good = [x(&pairs_a)]; - direct - .compute_group(gu, down, &BorrowedGroup { tokens: &tokens, experts: &good, stride: TOP_K }, &mut out) - .expect("good group"); - assert!(out[H..2 * H].iter().all(|v| v.is_finite())); + serves_good_group(&mut sink, &bank, &tokens); } /// The previous runtime prepare step per expert also copied each role out of the source (`block`) and /// scanned every block header (`encoded_finite`) before `PreparedJob::new` copied them again. -fn owned_path_with_source_copy( - pool: &mut CpuPool, - gu: GateUpFormat, - down: DownFormat, - bank: &[Expert], - tokens: &[f32], - jobs: &[(usize, Vec<(usize, usize)>)], - out: &mut [f32], -) { - let (_, gb) = gate_up_block(gu); - let (_, db) = down_block(down); +fn prepare_source_copy(w: &Work, e: usize, pairs: &[(usize, usize)]) -> PreparedJob { + let (_, gb) = gate_up_block(w.gu); + let (_, db) = down_block(w.down); let scan = |bytes: &[u8], block: usize| { bytes.chunks_exact(block).all(|b| u16::from_le_bytes([b[0], b[1]]) & 0x7c00 != 0x7c00) }; - for batch in jobs.chunks(OLD_BATCH) { - let mut prepared = Vec::with_capacity(batch.len()); - for (e, pairs) in batch { - let x = &bank[*e]; - let (g, u, d) = - (x.gate.clone().into_boxed_slice(), x.up.clone().into_boxed_slice(), x.down.clone().into_boxed_slice()); - assert!(scan(&g, gb) && scan(&u, gb) && scan(&d, db)); - let mut input = Vec::with_capacity(pairs.len() * H); - for &(row, _) in pairs { - input.extend_from_slice(&tokens[row * H..(row + 1) * H]); - } - prepared - .push(PreparedJob::new(gu, down, g, u, d, input.into_boxed_slice(), pairs.len()).expect("owned job")); - } - let done = pool.start(prepared, 48 << 20).expect("start").join().expect("join"); - for (job, (_, pairs)) in done.into_iter().zip(batch) { - let values = job.into_values(); - for (i, &(row, slot)) in pairs.iter().enumerate() { - let at = (row * TOP_K + slot) * H; - out[at..at + H].copy_from_slice(&values[i * H..(i + 1) * H]); - } - } - } + let x = &w.bank[e]; + let (g, u, d) = + (x.gate.clone().into_boxed_slice(), x.up.clone().into_boxed_slice(), x.down.clone().into_boxed_slice()); + assert!(scan(&g, gb) && scan(&u, gb) && scan(&d, db)); + let input = gather_input(w.tokens, pairs); + PreparedJob::new(w.gu, w.down, g, u, d, input.into_boxed_slice(), pairs.len()).expect("owned job") +} + +fn owned_path_with_source_copy(pool: &mut CpuPool, w: &Work, out: &mut [f32]) { + run_owned(pool, w, out, prepare_source_copy); } /// Model-free cost of one decode round's CPU share: 48 groups of `GROUP_ROWS` rows, `GROUP_SHARE`% of the @@ -335,40 +386,8 @@ fn owned_path_with_source_copy( #[test] #[ignore = "benchmark; prints the cost of both group paths"] fn group_path_cost() { - let env = |name: &str, default: usize| std::env::var(name).ok().and_then(|v| v.parse().ok()).unwrap_or(default); - let workers = env("BENCH_WORKERS", 15) as i32; - let rows = env("GROUP_ROWS", 4); - let share = env("GROUP_SHARE", 50); - let rounds = env("ROUNDS", 5); - let (gu, down) = (GateUpFormat::Iq3S, DownFormat::Iq4Nl); - let mut rng = Rng(42); - let bank = bank(&mut rng, gu, down, env("BANK_EXPERTS", 256)); - let mut owned = CpuPool::new(workers).expect("owned pool"); - let mut direct = DirectCpuPool::new(workers).expect("direct pool"); - let groups: Vec<(Vec, Vec<(usize, Vec<(usize, usize)>)>)> = (0..48 * rounds) - .map(|_| { - let (ids, include) = route(&mut rng, rows, bank.len(), share); - ((0..rows * H).map(|_| rng.unit()).collect(), plan(&ids, &include)) - }) - .collect(); - let experts: usize = groups.iter().map(|(_, j)| j.len()).sum(); - let mut out = vec![0.0f32; rows * TOP_K * H]; - for arm in ["owned+source-copy", "owned", "borrowed", "owned+source-copy", "owned", "borrowed"] { - let started = Instant::now(); - for (tokens, jobs) in &groups { - match arm { - "borrowed" => borrowed_path(&mut direct, gu, down, &bank, tokens, jobs, &mut out), - "owned" => owned_path(&mut owned, gu, down, &bank, tokens, jobs, &mut out), - _ => owned_path_with_source_copy(&mut owned, gu, down, &bank, tokens, jobs, &mut out), - } - } - let ms = started.elapsed().as_secs_f64() * 1e3; - let gb = experts as f64 * (bank[0].gate.len() * 2 + bank[0].down.len()) as f64 / 1e9; - eprintln!( - "BENCH {arm:>18}: workers={workers} rows={rows} share={share}% {:.2} experts/group, {:.2} ms/round (48 groups), {:.1} GB/s of expert bytes", - experts as f64 / groups.len() as f64, - ms / rounds as f64, - gb / (ms / 1e3) - ); - } + bench::run(); } + +#[path = "borrowed_group_parity/bench.rs"] +mod bench; diff --git a/crates/native-cpu-expert/tests/borrowed_group_parity/bench.rs b/crates/native-cpu-expert/tests/borrowed_group_parity/bench.rs new file mode 100644 index 00000000..54e46b84 --- /dev/null +++ b/crates/native-cpu-expert/tests/borrowed_group_parity/bench.rs @@ -0,0 +1,75 @@ +//! The model-free cost benchmark of both group paths, run by the ignored test `group_path_cost`. + +use super::*; +use std::time::Instant; + +fn env(name: &str, default: usize) -> usize { + std::env::var(name).ok().and_then(|v| v.parse().ok()).unwrap_or(default) +} + +/// The shape of the benchmark: workers and per-group rows, CPU share and rounds. +struct Cfg { + workers: i32, + rows: usize, + share: usize, + rounds: usize, +} + +/// The tokens of a group and its planned experts. +type Group = (Vec, Vec); + +fn make_groups(rng: &mut Rng, bank: &[Expert], cfg: &Cfg) -> Vec { + (0..48 * cfg.rounds) + .map(|_| { + let (ids, include) = route(rng, cfg.rows, bank.len(), cfg.share); + ((0..cfg.rows * H).map(|_| rng.unit()).collect(), plan(&ids, &include)) + }) + .collect() +} + +/// Milliseconds one arm needs for every group. +fn time_arm(arm: &str, pools: &mut Pools, base: Work, groups: &[Group], out: &mut [f32]) -> f64 { + let started = Instant::now(); + for (tokens, jobs) in groups { + let w = Work { tokens, jobs, ..base }; + match arm { + "borrowed" => borrowed_path(&mut pools.direct, &w, out), + "owned" => owned_path(&mut pools.owned, &w, out), + _ => owned_path_with_source_copy(&mut pools.owned, &w, out), + } + } + started.elapsed().as_secs_f64() * 1e3 +} + +/// One result line: `per_group` experts per group, `(ms, gb)` the time of the arm and the expert bytes it moved. +fn report(arm: &str, cfg: &Cfg, per_group: f64, (ms, gb): (f64, f64)) { + let (workers, rows, share, rounds) = (cfg.workers, cfg.rows, cfg.share, cfg.rounds); + eprintln!( + "BENCH {arm:>18}: workers={workers} rows={rows} share={share}% {:.2} experts/group, {:.2} ms/round (48 \ + groups), {:.1} GB/s of expert bytes", + per_group, + ms / rounds as f64, + gb / (ms / 1e3) + ); +} + +pub(super) fn run() { + let workers = env("BENCH_WORKERS", 15) as i32; + let cfg = Cfg { workers, rows: env("GROUP_ROWS", 4), share: env("GROUP_SHARE", 50), rounds: env("ROUNDS", 5) }; + let (gu, down) = (GateUpFormat::Iq3S, DownFormat::Iq4Nl); + let mut rng = Rng(42); + let bank = bank(&mut rng, gu, down, env("BANK_EXPERTS", 256)); + let mut pools = Pools { + owned: CpuPool::new(workers).expect("owned pool"), + direct: DirectCpuPool::new(workers).expect("direct pool"), + }; + let groups = make_groups(&mut rng, &bank, &cfg); + let experts: usize = groups.iter().map(|(_, j)| j.len()).sum(); + let mut out = vec![0.0f32; cfg.rows * TOP_K * H]; + let base = Work { gu, down, bank: &bank, tokens: &[], jobs: &[] }; + let gb = experts as f64 * (bank[0].gate.len() * 2 + bank[0].down.len()) as f64 / 1e9; + for arm in ["owned+source-copy", "owned", "borrowed", "owned+source-copy", "owned", "borrowed"] { + let ms = time_arm(arm, &mut pools, base, &groups, &mut out); + report(arm, &cfg, experts as f64 / groups.len() as f64, (ms, gb)); + } +} diff --git a/crates/native-cpu-expert/tests/cpu_pool_probe.rs b/crates/native-cpu-expert/tests/cpu_pool_probe.rs index 2d34aecb..40dcf8ec 100644 --- a/crates/native-cpu-expert/tests/cpu_pool_probe.rs +++ b/crates/native-cpu-expert/tests/cpu_pool_probe.rs @@ -33,6 +33,47 @@ fn down_block(f: DownFormat) -> (usize, usize) { } } +/// A zero-filled job of one format pair (valid FP16 headers, so finite) over a constant activation. +fn new_job(gu: GateUpFormat, down: DownFormat, rows: usize) -> Result { + let (gq, gb) = gate_up_block(gu); + let (dq, db) = down_block(down); + let gsize = H / gq * gb * FF; + let dsize = FF / dq * db * H; + let input = vec![0.5f32; rows * H].into_boxed_slice(); + PreparedJob::new( + gu, + down, + vec![0u8; gsize].into_boxed_slice(), + vec![0u8; gsize].into_boxed_slice(), + vec![0u8; dsize].into_boxed_slice(), + input, + rows, + ) +} + +/// Runs one job of the pair through the pool and reports whether the rows come back finite. +fn probe_pair(pool: &mut CpuPool, rows: usize, gu: GateUpFormat, down: DownFormat) { + let job = match new_job(gu, down, rows) { + Ok(job) => job, + Err(e) => { + eprintln!("PREFLIGHT PreparedJob::new({gu:?}, {down:?}) ERR: {e:?}"); + return; + } + }; + let started = std::time::Instant::now(); + let result = pool.start(vec![job], 48 << 20).and_then(|pending| pending.join()); + match result { + Ok(done) => { + let finite = done.into_iter().all(|j| j.into_values().iter().all(|v| v.is_finite())); + eprintln!( + "PREFLIGHT cpu expert {gu:?} x {down:?} rows={rows} ok finite={finite} in {:?}", + started.elapsed() + ); + } + Err(e) => eprintln!("PREFLIGHT cpu expert {gu:?} x {down:?} ERR: {e:?}"), + } +} + #[test] #[ignore = "bring-up probe; no model"] fn cpu_pool_runs_every_expert_format_pair() { @@ -47,38 +88,7 @@ fn cpu_pool_runs_every_expert_format_pair() { let downs = [DownFormat::Iq4Nl, DownFormat::Q2_0]; for gu in gates { for down in downs { - let (gq, gb) = gate_up_block(gu); - let (dq, db) = down_block(down); - let gsize = H / gq * gb * FF; - let dsize = FF / dq * db * H; - let input = vec![0.5f32; rows * H].into_boxed_slice(); - let job = match PreparedJob::new( - gu, - down, - vec![0u8; gsize].into_boxed_slice(), - vec![0u8; gsize].into_boxed_slice(), - vec![0u8; dsize].into_boxed_slice(), - input, - rows, - ) { - Ok(job) => job, - Err(e) => { - eprintln!("PREFLIGHT PreparedJob::new({gu:?}, {down:?}) ERR: {e:?}"); - continue; - } - }; - let started = std::time::Instant::now(); - let result = pool.start(vec![job], 48 << 20).and_then(|pending| pending.join()); - match result { - Ok(done) => { - let finite = done.into_iter().all(|j| j.into_values().iter().all(|v| v.is_finite())); - eprintln!( - "PREFLIGHT cpu expert {gu:?} x {down:?} rows={rows} ok finite={finite} in {:?}", - started.elapsed() - ); - } - Err(e) => eprintln!("PREFLIGHT cpu expert {gu:?} x {down:?} ERR: {e:?}"), - } + probe_pair(&mut pool, rows, gu, down); } } } diff --git a/crates/native-cpu-expert/tests/cpu_service_bench.rs b/crates/native-cpu-expert/tests/cpu_service_bench.rs index d531be3e..ed3f749a 100644 --- a/crates/native-cpu-expert/tests/cpu_service_bench.rs +++ b/crates/native-cpu-expert/tests/cpu_service_bench.rs @@ -1,10 +1,12 @@ -//! Model-free timing of the serve path's CPU expert dispatch (`DirectCpuPool::compute_group`, the call one verify-window layer makes): -//! IQ3_S gate/up and IQ4_NL down experts of the Flash-Next shape (H 2560, FF 640) with random valid blocks, cycled over EXPERTS distinct -//! experts (default 256, ~600 MB, past every L3) so every call reads its weights from DRAM as the decode does. Prints microseconds per call -//! and, with LELEKA_POOL_TIMING=1, the host's stage split (see `POOL_TIMING_NAMES`). +//! Model-free timing of the serve path's CPU expert dispatch (`DirectCpuPool::compute_group`, the call one +//! verify-window layer makes): IQ3_S gate/up and IQ4_NL down experts of the Flash-Next shape (H 2560, FF 640) with +//! random valid blocks, cycled over EXPERTS distinct experts (default 256, ~600 MB, past every L3) so every +//! call reads its weights from DRAM as the decode does. Prints microseconds per call and, with +//! LELEKA_POOL_TIMING=1, the host's stage split (see `POOL_TIMING_NAMES`). //! //! BENCH_WORKERS (default 15) BENCH_EXPERTS (default 256) BENCH_CALLS (default 2000) -//! LELEKA_POOL_TIMING=1 cargo test --release -p leleka-native-cpu-expert --test cpu_service_bench -- --ignored --nocapture +//! LELEKA_POOL_TIMING=1 cargo test --release -p leleka-native-cpu-expert --test cpu_service_bench -- --ignored +//! --nocapture use leleka_native_cpu_expert::{ BorrowedExpert, BorrowedGroup, DirectCpuPool, DownFormat, GateUpFormat, POOL_TIMING_NAMES, }; @@ -47,6 +49,152 @@ struct Expert { down: Vec, } +/// The pool, the expert bank (cycled over, so every call reads cold weights) and the buffers of the benchmark. +struct Bench { + pool: DirectCpuPool, + experts: Vec, + tokens: Vec, + out: Vec, + calls: usize, +} + +/// (label, rows in the window, per expert: the token rows it serves) +type Shape<'a> = (&'a str, usize, &'a [&'a [usize]]); + +/// The scan written with an early-exit branch per block (main). +fn scan_early_exit(m: &[u8], block: usize) -> bool { + for b in m.chunks_exact(block) { + if u16::from_le_bytes([b[0], b[1]]) & 0x7c00 == 0x7c00 { + return true; + } + } + false +} + +/// The scan written branch-free. +fn scan_branch_free(m: &[u8], block: usize) -> bool { + let mut acc = 0u32; + for b in m.chunks_exact(block) { + acc |= u32::from(u16::from_le_bytes([b[0], b[1]]) & 0x7c00 == 0x7c00); + } + acc != 0 +} + +/// The single-threaded admission scan of an expert: every block's FP16 scale, as `encoded_finite::validate_row`. +fn scan_expert(x: &Expert, branch_free: bool) -> bool { + let mut bad = false; + for (m, block) in [(&x.gate, 110usize), (&x.up, 110), (&x.down, 18)] { + bad |= if branch_free { scan_branch_free(m, block) } else { scan_early_exit(m, block) }; + } + bad +} + +impl Bench { + /// One window: `members.len()` experts, each serving the listed token rows. + fn shape_call(&mut self, (rows, members): (usize, &[&[usize]]), next: &mut usize) { + let pairs: Vec> = + members.iter().enumerate().map(|(slot, toks)| toks.iter().map(|&t| (t, slot)).collect()).collect(); + let group_experts: Vec> = pairs + .iter() + .map(|p| { + let x = &self.experts[*next % self.experts.len()]; + *next += 1; + BorrowedExpert { gate: &x.gate, up: &x.up, down: &x.down, pairs: p } + }) + .collect(); + let group = BorrowedGroup { tokens: &self.tokens[..rows * H], experts: &group_experts, stride: TOP_K }; + self.pool + .compute_group(GateUpFormat::Iq3S, DownFormat::Iq4Nl, &group, &mut self.out[..rows * TOP_K * H]) + .expect("compute_group"); + } + + /// The result line of one shape: microseconds per call and per expert, GB/s, and the host's stage split. + fn shape_line(&mut self, pass: usize, label: &str, (n_members, us): (usize, f64)) -> String { + let n = n_members as f64; + let mut line = format!( + "pass {pass} {label}: {us:.1} us per call, {:.1} us per expert, {:.1} GB/s", + us / n, + n * 2.33e6 / us / 1e3 + ); + if let Some(t) = self.pool.take_timing() { + line.push_str(" |"); + for (name, ms) in POOL_TIMING_NAMES.iter().zip(t) { + line.push_str(&format!(" {}={:.1}", name.trim_start_matches("cpu.t."), ms * 1e3 / self.calls as f64)); + } + } + line + } + + fn run_shape(&mut self, pass: usize, (label, rows, members): Shape) { + let mut next = 0usize; + let _ = self.pool.take_timing(); + let start = std::time::Instant::now(); + for _ in 0..self.calls { + self.shape_call((rows, members), &mut next); + } + let us = start.elapsed().as_secs_f64() * 1e6 / self.calls as f64; + let line = self.shape_line(pass, label, (members.len(), us)); + eprintln!("{line}"); + } + + /// First use of an expert in the serve path: the single-threaded admission scan then the compute. + fn first_use(&mut self, pass: usize, branch_free: bool) { + let mut next = 0usize; + let pairs = [(0usize, 0usize)]; + let start = std::time::Instant::now(); + let mut t_scan = 0.0f64; + for _ in 0..self.calls { + let x = &self.experts[next % self.experts.len()]; + next += 1; + let t1 = std::time::Instant::now(); + assert!(!std::hint::black_box(scan_expert(x, branch_free))); + t_scan += t1.elapsed().as_secs_f64(); + let e = [BorrowedExpert { gate: &x.gate, up: &x.up, down: &x.down, pairs: &pairs }]; + let group = BorrowedGroup { tokens: &self.tokens[..H], experts: &e, stride: TOP_K }; + self.pool + .compute_group(GateUpFormat::Iq3S, DownFormat::Iq4Nl, &group, &mut self.out[..TOP_K * H]) + .expect("compute_group"); + } + let _ = self.pool.take_timing(); + eprintln!( + "pass {pass} first use, branch_free={branch_free}: {:.1} us per expert (scan {:.1}, compute the rest)", + start.elapsed().as_secs_f64() * 1e6 / self.calls as f64, + t_scan * 1e6 / self.calls as f64 + ); + } +} + +fn make_experts(rng: &mut Rng, count: usize) -> Vec { + (0..count) + .map(|_| Expert { + gate: blocks(rng, FF * H / 256, 110), + up: blocks(rng, FF * H / 256, 110), + down: blocks(rng, H * FF / 32, 18), + }) + .collect() +} + +/// The pool, or None (with a note) where it does not start. +fn open_pool(workers: i32) -> Option { + match DirectCpuPool::new(workers) { + Ok(p) => Some(p), + Err(e) => { + eprintln!("SKIP: pool did not start ({e:?})"); + None + } + } +} + +fn shapes() -> [Shape<'static>; 5] { + [ + ("1 expert x 1 token", 1, &[&[0]]), + ("2 experts x 1 token", 2, &[&[0], &[1]]), + ("3 experts x 1 token", 3, &[&[0], &[1], &[2]]), + ("1 expert x 2 tokens", 2, &[&[0, 1]]), + ("1 expert x 3 tokens", 3, &[&[0, 1, 2]]), + ] +} + #[test] #[ignore = "benchmark; no model"] fn cpu_service_bench() { @@ -54,107 +202,18 @@ fn cpu_service_bench() { let n_experts = env_usize("BENCH_EXPERTS", 256); let calls = env_usize("BENCH_CALLS", 2000); let mut rng = Rng(0x5eed_cafe_f00d_1234); - let experts: Vec = (0..n_experts) - .map(|_| Expert { - gate: blocks(&mut rng, FF * H / 256, 110), - up: blocks(&mut rng, FF * H / 256, 110), - down: blocks(&mut rng, H * FF / 32, 18), - }) - .collect(); - let mut pool = match DirectCpuPool::new(workers) { - Ok(p) => p, - Err(e) => { - eprintln!("SKIP: pool did not start ({e:?})"); - return; - } - }; + let experts = make_experts(&mut rng, n_experts); + let Some(pool) = open_pool(workers) else { return }; let tokens_max = 4usize; let tokens: Vec = (0..tokens_max * H).map(|_| (rng.next() % 2001) as f32 / 1000.0 - 1.0).collect(); - let mut out = vec![0.0f32; tokens_max * TOP_K * H]; - // (label, rows in the window, per expert: the token rows it serves) - let shapes: [(&str, usize, &[&[usize]]); 5] = [ - ("1 expert x 1 token", 1, &[&[0]]), - ("2 experts x 1 token", 2, &[&[0], &[1]]), - ("3 experts x 1 token", 3, &[&[0], &[1], &[2]]), - ("1 expert x 2 tokens", 2, &[&[0, 1]]), - ("1 expert x 3 tokens", 3, &[&[0, 1, 2]]), - ]; + let out = vec![0.0f32; tokens_max * TOP_K * H]; + let mut bench = Bench { pool, experts, tokens, out, calls }; for pass in 0..2 { - for (label, rows, members) in shapes { - let mut next = 0usize; - let _ = pool.take_timing(); - let start = std::time::Instant::now(); - for _ in 0..calls { - let pairs: Vec> = - members.iter().enumerate().map(|(slot, toks)| toks.iter().map(|&t| (t, slot)).collect()).collect(); - let group_experts: Vec> = pairs - .iter() - .map(|p| { - let x = &experts[next % n_experts]; - next += 1; - BorrowedExpert { gate: &x.gate, up: &x.up, down: &x.down, pairs: p } - }) - .collect(); - let group = BorrowedGroup { tokens: &tokens[..rows * H], experts: &group_experts, stride: TOP_K }; - pool.compute_group(GateUpFormat::Iq3S, DownFormat::Iq4Nl, &group, &mut out[..rows * TOP_K * H]) - .expect("compute_group"); - } - let us = start.elapsed().as_secs_f64() * 1e6 / calls as f64; - let n = members.len() as f64; - let mut line = format!( - "pass {pass} {label}: {us:.1} us per call, {:.1} us per expert, {:.1} GB/s", - us / n, - n * 2.33e6 / us / 1e3 - ); - if let Some(t) = pool.take_timing() { - line.push_str(" |"); - for (name, ms) in POOL_TIMING_NAMES.iter().zip(t) { - line.push_str(&format!(" {}={:.1}", name.trim_start_matches("cpu.t."), ms * 1e3 / calls as f64)); - } - } - eprintln!("{line}"); + for shape in shapes() { + bench.run_shape(pass, shape); } - // First use of an expert in the serve path: the single-threaded admission scan (every block's FP16 scale, as - // `encoded_finite::validate_row`) then the compute; the scan written with an early-exit branch per block (main) and branch-free. for branch_free in [false, true] { - let mut next = 0usize; - let pairs = [(0usize, 0usize)]; - let start = std::time::Instant::now(); - let mut t_scan = 0.0f64; - for _ in 0..calls { - let x = &experts[next % n_experts]; - next += 1; - let t1 = std::time::Instant::now(); - let mut bad = false; - for (m, block) in [(&x.gate, 110usize), (&x.up, 110), (&x.down, 18)] { - if branch_free { - let mut acc = 0u32; - for b in m.chunks_exact(block) { - acc |= u32::from(u16::from_le_bytes([b[0], b[1]]) & 0x7c00 == 0x7c00); - } - bad |= acc != 0; - } else { - for b in m.chunks_exact(block) { - if u16::from_le_bytes([b[0], b[1]]) & 0x7c00 == 0x7c00 { - bad = true; - break; - } - } - } - } - assert!(!std::hint::black_box(bad)); - t_scan += t1.elapsed().as_secs_f64(); - let e = [BorrowedExpert { gate: &x.gate, up: &x.up, down: &x.down, pairs: &pairs }]; - let group = BorrowedGroup { tokens: &tokens[..H], experts: &e, stride: TOP_K }; - pool.compute_group(GateUpFormat::Iq3S, DownFormat::Iq4Nl, &group, &mut out[..TOP_K * H]) - .expect("compute_group"); - } - let _ = pool.take_timing(); - eprintln!( - "pass {pass} first use, branch_free={branch_free}: {:.1} us per expert (scan {:.1}, compute the rest)", - start.elapsed().as_secs_f64() * 1e6 / calls as f64, - t_scan * 1e6 / calls as f64 - ); + bench.first_use(pass, branch_free); } } } diff --git a/crates/native-cpu-expert/tests/pool_lifecycle.rs b/crates/native-cpu-expert/tests/pool_lifecycle.rs index aeda8c4d..e9e12317 100644 --- a/crates/native-cpu-expert/tests/pool_lifecycle.rs +++ b/crates/native-cpu-expert/tests/pool_lifecycle.rs @@ -108,8 +108,8 @@ fn run( pool.compute_group(GU, DOWN, &BorrowedGroup { tokens, experts: &experts, stride: STRIDE }, out) } -/// Dropping the pool must stop AND join every worker: no thread may outlive it (a worker that survived `Drop` could still -/// hold raw pointers into caller memory), including after a refused (non-finite) group. +/// Dropping the pool must stop AND join every worker: no thread may outlive it (a worker that survived `Drop` could +/// still hold raw pointers into caller memory), including after a refused (non-finite) group. #[test] fn dropping_the_pool_joins_every_worker() { let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner()); @@ -129,10 +129,10 @@ fn dropping_the_pool_joins_every_worker() { } } -/// Back-to-back groups separated by idle gaps shorter and longer than the 20 ms spin window (workers spinning, then asleep -/// on the condvar, then woken while a new epoch is published) must stay bit-identical to the first result. A delayed -/// sleeper carrying an old epoch into the claim, or a host that mutated the batch before every worker parked, would show -/// up as a changed or missing output row. +/// Back-to-back groups separated by idle gaps shorter and longer than the 20 ms spin window (workers spinning, then +/// asleep on the condvar, then woken while a new epoch is published) must stay bit-identical to the first +/// result. A delayed sleeper carrying an old epoch into the claim, or a host that mutated the batch before every +/// worker parked, would show up as a changed or missing output row. #[test] fn repeated_groups_across_idle_gaps_are_bit_identical() { let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner()); @@ -174,22 +174,20 @@ fn settles_named(prefix: &str, expected: usize) -> bool { threads_named(prefix) == expected } -/// The owned-batch coordinator (`CpuPool`: a coordinator thread that owns the native pool, jobs moved by value) must join the -/// coordinator and all its workers on drop, after a completed batch. -#[test] -fn owned_pool_drop_joins_coordinator_and_workers() { - use leleka_native_cpu_expert::{CpuPool, PreparedJob}; - let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner()); - assert_eq!(threads_named("leleka-cpu-miss"), 0); - let mut owned = match CpuPool::new(2) { - Ok(pool) => pool, +/// The owned-batch pool of two workers, or None (with a note) where it is unavailable. +fn owned_pool() -> Option { + match leleka_native_cpu_expert::CpuPool::new(2) { + Ok(pool) => Some(pool), Err(error) => { eprintln!("SKIP: CPU expert pool unavailable here: {error:?}"); - return; + None } - }; - let bank = bank(1); - let job = PreparedJob::new( + } +} + +/// The first expert of `bank` as one owned job over a single token row. +fn prepared_job(bank: &[Expert]) -> leleka_native_cpu_expert::PreparedJob { + leleka_native_cpu_expert::PreparedJob::new( GU, DOWN, bank[0].gate.clone().into_boxed_slice(), @@ -198,8 +196,18 @@ fn owned_pool_drop_joins_coordinator_and_workers() { tokens(1).into_boxed_slice(), 1, ) - .expect("prepared job"); - let done = owned.start(vec![job], 64 << 20).expect("start").join().expect("join"); + .expect("prepared job") +} + +/// The owned-batch coordinator (`CpuPool`: a coordinator thread that owns the native pool, jobs moved by value) must +/// join the coordinator and all its workers on drop, after a completed batch. +#[test] +fn owned_pool_drop_joins_coordinator_and_workers() { + let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner()); + assert_eq!(threads_named("leleka-cpu-miss"), 0); + let Some(mut owned) = owned_pool() else { return }; + let bank = bank(1); + let done = owned.start(vec![prepared_job(&bank)], 64 << 20).expect("start").join().expect("join"); assert_eq!(done.len(), 1); assert!(done.into_iter().next().expect("one job").into_values().iter().all(|v| v.is_finite())); assert_eq!(threads_named("leleka-cpu-miss"), 1); diff --git a/crates/native-cpu-expert/tests/token_count_invariance.rs b/crates/native-cpu-expert/tests/token_count_invariance.rs index b7ed0664..a36225a8 100644 --- a/crates/native-cpu-expert/tests/token_count_invariance.rs +++ b/crates/native-cpu-expert/tests/token_count_invariance.rs @@ -1,8 +1,9 @@ -//! STRA-329: a token's expert output must not depend on how many other tokens share its expert once the multi-token kernels are in -//! (from `STRATA_IQ_MT_MIN`, default 2 tokens; native_expert.cpp native_gu_rows "#152"). Checks every gate/up x down pair, including the -//! IQ2_XXS / IQ2_XS gate/up the KAB1 `ext` case set adds, at every token count 2..=8: the first two tokens of a group of n tokens must -//! equal, bit for bit, the same two tokens run as a group of two. One token is excluded on purpose (ggml's per-token dot rounds -//! differently, the very reason for the rule). Rust only: no C++ reference, no GPU. Synthetic blobs: random codes, finite FP16 scales. +//! STRA-329: a token's expert output must not depend on how many other tokens share its expert once the multi-token +//! kernels are in (from `STRATA_IQ_MT_MIN`, default 2 tokens; native_expert.cpp native_gu_rows "#152"). Checks +//! every gate/up x down pair, including the IQ2_XXS / IQ2_XS gate/up the KAB1 `ext` case set adds, at every +//! token count 2..=8: the first two tokens of a group of n tokens must equal, bit for bit, the same two tokens +//! run as a group of two. One token is excluded on purpose (ggml's per-token dot rounds differently, the very +//! reason for the rule). Rust only: no C++ reference, no GPU. Synthetic blobs: random codes, finite FP16 scales. //! //! cargo test -p leleka-native-cpu-expert --test token_count_invariance use leleka_native_cpu_expert::{CpuPool, DownFormat, GateUpFormat, PreparedJob}; @@ -50,8 +51,7 @@ fn matrix(rng: &mut Rng, bytes: usize, block: usize) -> Vec { fn run( pool: &mut CpuPool, - gu: GateUpFormat, - down: DownFormat, + (gu, down): (GateUpFormat, DownFormat), blobs: &[Vec; 3], tokens: &[f32], n: usize, @@ -74,41 +74,55 @@ fn run( done.into_iter().next().expect("one job").into_values().to_vec() } +const GATES: [GateUpFormat; 7] = [ + GateUpFormat::Iq2Xxs, + GateUpFormat::Iq2Xs, + GateUpFormat::Iq3Xxs, + GateUpFormat::Iq3S, + GateUpFormat::Iq2S, + GateUpFormat::Iq4Xs, + GateUpFormat::Q2_0, +]; + +/// The gate, up and down blobs of one format pair. +fn blobs_for(rng: &mut Rng, gu: GateUpFormat, down: DownFormat) -> [Vec; 3] { + let (gq, gb) = gate_up_block(gu); + let (dq, db) = down_block(down); + [matrix(rng, H / gq * gb * FF, gb), matrix(rng, H / gq * gb * FF, gb), matrix(rng, FF / dq * db * H, db)] +} + +fn random_tokens(rng: &mut Rng) -> Vec { + (0..8 * H).map(|_| (rng.next() >> 40) as f32 / (1u64 << 24) as f32 * 2.0 - 1.0).collect() +} + +/// The first two tokens of a group of `n` tokens equal, bit for bit, the same two tokens run as a group of two. +fn assert_first_two_equal(base: &[f32], wide: &[f32], (gu, down): (GateUpFormat, DownFormat), n: usize) { + for i in 0..2 * H { + assert_eq!( + wide[i].to_bits(), + base[i].to_bits(), + "{gu:?} + {down:?}: {n} tokens differ from 2 tokens at output {i}" + ); + } +} + +/// One format pair at every token count 3..=8 against the group of two. +fn check_pair(pool: &mut CpuPool, rng: &mut Rng, pair: (GateUpFormat, DownFormat)) { + let blobs = blobs_for(rng, pair.0, pair.1); + let tokens = random_tokens(rng); + let base = run(pool, pair, &blobs, &tokens, 2); + for n in 3..=8 { + assert_first_two_equal(&base, &run(pool, pair, &blobs, &tokens, n), pair, n); + } +} + #[test] fn the_first_two_tokens_do_not_depend_on_the_group_size() { let mut pool = CpuPool::new(1).expect("pool"); let mut rng = Rng(0x0329_5eed_9e37_79b9); - let gates = [ - GateUpFormat::Iq2Xxs, - GateUpFormat::Iq2Xs, - GateUpFormat::Iq3Xxs, - GateUpFormat::Iq3S, - GateUpFormat::Iq2S, - GateUpFormat::Iq4Xs, - GateUpFormat::Q2_0, - ]; - for gu in gates { + for gu in GATES { for down in [DownFormat::Iq4Nl, DownFormat::Q2_0] { - let (gq, gb) = gate_up_block(gu); - let (dq, db) = down_block(down); - let blobs = [ - matrix(&mut rng, H / gq * gb * FF, gb), - matrix(&mut rng, H / gq * gb * FF, gb), - matrix(&mut rng, FF / dq * db * H, db), - ]; - let tokens: Vec = - (0..8 * H).map(|_| ((rng.next() >> 40) as f32 / (1u64 << 24) as f32 * 2.0 - 1.0)).collect(); - let base = run(&mut pool, gu, down, &blobs, &tokens, 2); - for n in 3..=8 { - let wide = run(&mut pool, gu, down, &blobs, &tokens, n); - for i in 0..2 * H { - assert_eq!( - wide[i].to_bits(), - base[i].to_bits(), - "{gu:?} + {down:?}: {n} tokens differ from 2 tokens at output {i}" - ); - } - } + check_pair(&mut pool, &mut rng, (gu, down)); } } }