diff --git a/crates/native-cpu-expert/examples/kernel_ab/alternate_run.rs b/crates/native-cpu-expert/examples/kernel_ab/alternate_run.rs deleted file mode 100644 index 944a3622..00000000 --- a/crates/native-cpu-expert/examples/kernel_ab/alternate_run.rs +++ /dev/null @@ -1,265 +0,0 @@ -//! The stages of the alternation runner (`kernel_ab alternate`) after the command line is parsed: the preparation -//! (paths, schedule file, host facts), the equality phase and the rounds. - -#[allow(unused_imports)] -use super::*; - -/// The rounds of a schedule: the round number and the processes in the order they run. -type Schedule = Vec<(u32, Vec)>; - -/// The paths the runner reads and writes. -pub(super) struct AltPaths { - pub(super) out: PathBuf, - pub(super) own_exe: PathBuf, - pub(super) kab: PathBuf, -} - -impl AltPaths { - pub(super) fn records_dir(&self) -> PathBuf { - self.out.join("records") - } - pub(super) fn proc_dir(&self) -> PathBuf { - self.out.join("processes") - } -} - -/// Facts about the host and the parent process, read once at the start. -pub(super) struct HostFacts { - pub(super) parent_env: Vec<(OsString, OsString)>, - pub(super) sibling_at_start: bool, - pub(super) machine_role: String, - pub(super) rustc_version: String, - pub(super) triple: String, -} - -/// What every stage of `alternate` reads. -pub(super) struct AltRun<'a> { - pub(super) a: &'a AltArgs, - pub(super) verified: &'a Verified, - pub(super) case: &'a CaseEntry, - pub(super) trees: Vec<&'static str>, - pub(super) procs: Vec, - pub(super) paths: AltPaths, - pub(super) schedule_text: String, - pub(super) first_round: u32, - pub(super) host: HostFacts, - pub(super) started: String, -} - -/// Chooses and checks the paths, writes the schedule file (before the first run) and reads the host facts. -/// Returns the run and the schedule read back from its file. -pub(super) fn prepare_alt_run<'a>( - a: &'a AltArgs, - verified: &'a Verified, - case: &'a CaseEntry, - started: String, -) -> Result<(AltRun<'a>, Schedule), String> { - let paths = resolve_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 first_round = (a.batch - 1) * a.rounds + 1; - let (schedule, schedule_text) = write_schedule(a, &paths.out, &procs, first_round)?; - create_run_dirs(&paths)?; - let host = read_host_facts(a); - let run = AltRun { a, verified, case, trees, procs, paths, schedule_text, first_round, host, started }; - Ok((run, schedule)) -} - -fn resolve_alt_paths(a: &AltArgs) -> Result { - let out = a.out.clone().unwrap_or_else(|| sibling_dir(&a.dir, &format!(".alt-{}", a.case))); - require_alt_paths(a, &out)?; - 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(default_kab); - if !kab.is_file() { - return Err(format!( - "the C++ driver {} does not exist (build tools/kernel-ab/cpp, or pass --kab / set KAB)", - kab.display() - )); - } - Ok(AltPaths { out, own_exe, kab }) -} - -/// The output lies outside the run directory and, with the schedule file, outside every Git checkout. -fn require_alt_paths(a: &AltArgs, out: &Path) -> Result<(), String> { - let abs = |p: &Path| std::path::absolute(p).unwrap_or_else(|_| p.to_path_buf()); - if abs(out).starts_with(abs(&a.dir)) || abs(&a.dir).starts_with(abs(out)) { - return Err("--out must not contain or lie inside the KAB1 directory".to_owned()); - } - if inside_git_checkout(out) || inside_git_checkout(&a.schedule) { - return Err( - "--out and --schedule must lie outside every Git checkout (generated artifacts stay out of Git)".to_owned() - ); - } - Ok(()) -} - -/// `$E2E_ROOT/build/kernel-ab/kab` (the root defaults to `$HOME/work/leleka-e2e`). -fn default_kab() -> PathBuf { - let root = std::env::var("E2E_ROOT") - .unwrap_or_else(|_| format!("{}/work/leleka-e2e", std::env::var("HOME").unwrap_or_default())); - PathBuf::from(root).join("build/kernel-ab/kab") -} - -/// 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], first_round: u32) -> Result<(Schedule, String), String> { - let planned = make_schedule(a.seed, a.batch, a.rounds, procs); - let text = schedule_text(a.seed, a.batch, a.rounds, &a.case, a.pin, first_round, &planned); - fs::create_dir_all(out).map_err(|e| format!("{}: {e}", out.display()))?; - if let Some(parent) = a.schedule.parent().filter(|p| !p.as_os_str().is_empty()) { - fs::create_dir_all(parent).map_err(|e| format!("{}: {e}", parent.display()))?; - } - create_new_file(&a.schedule, text.as_bytes())?; - let schedule = - parse_schedule(&fs::read_to_string(&a.schedule).map_err(|e| format!("{}: {e}", a.schedule.display()))?)?; - println!( - "schedule written to {} (sha256 {}) before the first run: {} rounds x {} processes", - a.schedule.display(), - sha_hex(text.as_bytes()), - schedule.len(), - procs.len() - ); - Ok((schedule, text)) -} - -fn create_run_dirs(paths: &AltPaths) -> Result<(), String> { - for d in [paths.records_dir(), paths.proc_dir()] { - fs::create_dir_all(&d).map_err(|e| format!("{}: {e}", d.display()))?; - } - Ok(()) -} - -fn read_host_facts(a: &AltArgs) -> HostFacts { - let parent_env: Vec<(OsString, OsString)> = std::env::vars_os().collect(); - let sibling_at_start = sibling_idle(a.pin); - let machine_role = machine_role_of(a.machine_role.as_deref()); - let (rustc_version, triple) = rustc_info(); - HostFacts { parent_env, sibling_at_start, machine_role, rustc_version, triple } -} - -// ------------------------------------------------------------------------------------------------ equality phase - -/// Our tree against the C++ reference .out file, per tree, in fresh processes (the kernels are not touched by timing). -pub(super) fn run_equality_phase(run: &AltRun) -> Result, String> { - let eq_dir = run.paths.out.join(format!("equality-b{:04}", run.a.batch)); - let mut equality = BTreeMap::new(); - for &tree in &run.trees { - let outcome = run_equality_tree(run, tree, &eq_dir)?; - println!( - "EQUALITY {} [{tree}] {}{}", - run.a.case, - if outcome.equal() { "EQUAL" } else { "NOT_EQUAL" }, - mismatch_detail(&outcome) - ); - equality.insert(tree, outcome); - } - Ok(equality) -} - -fn run_equality_tree(run: &AltRun, tree: &'static str, eq_dir: &Path) -> Result { - let a = run.a; - let p = Proc { imp: Impl::Rust, tree, rep: 'a' }; - let mut cmd = scrubbed_command(&run.paths.own_exe, &run.host.parent_env, &cell_env(&p)); - cmd.arg("run-tree") - .arg(&a.dir) - .args(["--tree", tree, "--case", &a.case, "--out"]) - .arg(eq_dir) - .args(["--pin", &a.pin.to_string()]); - run_cell(&mut cmd, &format!("{}/equality", p.name()))?; - let (ours, reference) = read_ours_and_reference(eq_dir, &a.dir, run.case, tree, tree)?; - Ok(compare_bits(&ours, &reference, run.case.tolerance.as_ref())) -} - -// ------------------------------------------------------------------------------------------------ rounds - -/// Runs every round of the schedule; returns the names of the round records written. -pub(super) fn run_rounds( - run: &AltRun, - schedule: &[(u32, Vec)], - equality: &BTreeMap<&'static str, Outcome>, -) -> Result, String> { - let mut ctx = batch_ctx(run, equality); - let expect = Expect { - manifest_sha: &run.verified.manifest_sha256, - input_sha: &run.case.in_sha256, - case: &run.a.case, - pin: run.a.pin, - }; - let mut written = Vec::new(); - for (round_no, order) in schedule { - let done: Vec = - order.iter().map(|p| run_timed_cell(run, &expect, *round_no, p)).collect::>()?; - 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 batch_file = run.paths.out.join(format!("batch-{:04}.json", run.a.batch)); - create_new_file(&batch_file, batch_json(run, &ctx.cpu_model, equality)?.as_bytes())?; - } - written.extend(write_round_records(run, &ctx, *round_no, &done)?); - println!("round {round_no} done: {}", order.iter().map(Proc::name).collect::>().join(" ")); - } - Ok(written) -} - -/// What a round record needs that does not change within a batch (the CPU model is filled in after the first round). -fn batch_ctx<'a>(run: &'a AltRun, equality: &'a BTreeMap<&'static str, Outcome>) -> BatchCtx<'a> { - BatchCtx { - verified: run.verified, - case: run.case, - pin: run.a.pin, - machine_role: run.host.machine_role.clone(), - os: host_os(), - cpu_model: String::new(), - started_utc: run.started.clone(), - rust_tool: Tool { - compiler: "rustc".to_owned(), - version: run.host.rustc_version.clone(), - triple: run.host.triple.clone(), - flags: ours_flags(), - }, - batch: run.a.batch, - equality, - } -} - -/// One fresh process of the round (`time` on the cell's implementation); its JSON is read back and checked. -fn run_timed_cell(run: &AltRun, expect: &Expect, round_no: u32, p: &Proc) -> Result { - let name = p.name(); - let file = run.paths.proc_dir().join(format!("r{round_no:05}-{name}.json")); - let mut cmd = time_command(run, p, &file); - 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()))?; - parse_proc_json(p, &bytes, expect) -} - -fn time_command(run: &AltRun, p: &Proc, file: &Path) -> Command { - let a = run.a; - let program = if p.imp == Impl::Cpp { &run.paths.kab } else { &run.paths.own_exe }; - let mut cmd = scrubbed_command(program, &run.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 -} - -/// Writes the records of one round (never over an existing file); returns their names. -fn write_round_records(run: &AltRun, ctx: &BatchCtx, round_no: u32, done: &[ProcOut]) -> Result, String> { - let records_dir = run.paths.records_dir(); - let mut names = Vec::new(); - for (name, json) in round_records(ctx, round_no, done)? { - create_new_file(&records_dir.join(&name), json.as_bytes())?; - names.push(name); - } - Ok(names) -} diff --git a/crates/native-cpu-expert/examples/kernel_ab/batch_json.rs b/crates/native-cpu-expert/examples/kernel_ab/batch_json.rs deleted file mode 100644 index 6bedbe01..00000000 --- a/crates/native-cpu-expert/examples/kernel_ab/batch_json.rs +++ /dev/null @@ -1,114 +0,0 @@ -//! The `batch-NNNN.json` file of the alternation runner: what a batch ran and on which host (it computes no -//! statistics). - -#[allow(unused_imports)] -use super::*; - -/// The batch file, written once after the first round (the CPU model comes from that round's processes). -pub(super) fn batch_json( - run: &AltRun, - cpu_model: &str, - equality: &BTreeMap<&'static str, Outcome>, -) -> Result { - let kab_sha = file_sha(&run.paths.kab)?; - let exe_sha = file_sha(&run.paths.own_exe)?; - let mut j = batch_json_run(run); - j += &batch_json_host(run, cpu_model); - j += &batch_json_files(run, &kab_sha, &exe_sha); - j += &batch_json_tail(run, equality); - Ok(j) -} - -/// The batch file from its opening brace through the input hash. -fn batch_json_run(run: &AltRun) -> String { - let (a, first_round) = (run.a, run.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(&run.started), - jstr(&a.case), - jstr(&a.dir.display().to_string()), - jstr(&run.verified.manifest_sha256), - jstr(&run.case.in_sha256) - ) -} - -/// The pin, the pool and the machine, and the seed. -fn batch_json_host(run: &AltRun, cpu_model: &str) -> String { - let sibling_at_start = run.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", - run.a.pin, - jstr(&run.host.machine_role), - jstr(cpu_model), - jstr(&host_os()), - run.a.seed - ) -} - -/// The schedule file, the C++ driver and this example with their hashes, and the slice settings. -fn batch_json_files(run: &AltRun, kab_sha: &str, exe_sha: &str) -> String { - let a = run.a; - 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(run.schedule_text.as_bytes())), - jstr(&run.paths.kab.display().to_string()), - jstr(kab_sha), - jstr(&run.paths.own_exe.display().to_string()), - jstr(exe_sha), - a.slices, - a.slice_ms.map_or("null".to_owned(), |m| jnum(m, 1)) - ) -} - -/// The equality verdicts, the cells and the closing note. -fn batch_json_tail(run: &AltRun, equality: &BTreeMap<&'static str, Outcome>) -> String { - format!( - " \"equality\": [{}],\n \"cells\": [{}],\n \"no_statistics\": \"this file computes no class, no interval \ - and \ - no A/A verdict (S0.10b, STRA-313)\"\n}}\n", - equality_json(run.case, equality), - cells_json(&run.procs) - ) -} - -fn equality_json(case: &CaseEntry, equality: &BTreeMap<&'static str, Outcome>) -> String { - 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(", ") -} - -fn cells_json(procs: &[Proc]) -> String { - 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(", ") -} 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 63f20906..81266af5 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 @@ -6,20 +6,218 @@ use super::*; pub(super) fn cmd_alternate(args: &[String]) -> Result { let a = parse_alt_args(args)?; let started = now_utc(); - let verified = match verify_or_exit(&a.dir) { + let verified = match verify_dir(&a.dir) { Ok(v) => v, - Err(code) => return Ok(code), + Err(e) => { + println!("{e}"); + return Ok(ExitCode::from(if e.incomplete { 2 } else { 1 })); + } }; - let case = find_case(&verified, &a.case)?.clone(); - let (run, schedule) = prepare_alt_run(&a, &verified, &case, started)?; - let equality = run_equality_phase(&run)?; - let written = run_rounds(&run, &schedule, &equality)?; + let case = verified + .cases + .iter() + .find(|c| c.id == a.case) + .ok_or_else(|| format!("case {} is not in the manifest", a.case))? + .clone(); + let out = a.out.clone().unwrap_or_else(|| { + let name = a.dir.file_name().map_or_else(|| "kab1".to_owned(), |n| n.to_string_lossy().into_owned()); + a.dir.parent().unwrap_or(Path::new(".")).join(format!("{name}.alt-{}", a.case)) + }); + let abs = |p: &Path| std::path::absolute(p).unwrap_or_else(|_| p.to_path_buf()); + if abs(&out).starts_with(abs(&a.dir)) || abs(&a.dir).starts_with(abs(&out)) { + return Err("--out must not contain or lie inside the KAB1 directory".to_owned()); + } + if inside_git_checkout(&out) || inside_git_checkout(&a.schedule) { + return Err( + "--out and --schedule must lie outside every Git checkout (generated artifacts stay out of Git)".to_owned() + ); + } + let own_exe = std::env::current_exe().map_err(|e| format!("current_exe: {e}"))?; + let kab = a.kab.clone().or_else(|| std::env::var_os("KAB").map(PathBuf::from)).unwrap_or_else(|| { + PathBuf::from( + std::env::var("E2E_ROOT") + .unwrap_or_else(|_| format!("{}/work/leleka-e2e", std::env::var("HOME").unwrap_or_default())), + ) + .join("build/kernel-ab/kab") + }); + if !kab.is_file() { + return Err(format!( + "the C++ driver {} does not exist (build tools/kernel-ab/cpp, or pass --kab / set KAB)", + kab.display() + )); + } + // a host without AVX-512 has no avx512 cells (the C++ reference trees are identical by construction there) + let trees: Vec<&'static str> = + TREES.iter().copied().filter(|t| *t != "avx512" || verified.provenance.avx512_ok != Some(false)).collect(); + let procs = procs_for(&trees); + + // the schedule, written BEFORE the first run and read back: the file, not the generator, drives the batch + let first_round = (a.batch - 1) * a.rounds + 1; + let planned = make_schedule(a.seed, a.batch, a.rounds, &procs); + let text = schedule_text(a.seed, a.batch, a.rounds, &a.case, a.pin, first_round, &planned); + fs::create_dir_all(&out).map_err(|e| format!("{}: {e}", out.display()))?; + if let Some(parent) = a.schedule.parent().filter(|p| !p.as_os_str().is_empty()) { + fs::create_dir_all(parent).map_err(|e| format!("{}: {e}", parent.display()))?; + } + create_new_file(&a.schedule, text.as_bytes())?; + let schedule = + parse_schedule(&fs::read_to_string(&a.schedule).map_err(|e| format!("{}: {e}", a.schedule.display()))?)?; + println!( + "schedule written to {} (sha256 {}) before the first run: {} rounds x {} processes", + a.schedule.display(), + sha_hex(text.as_bytes()), + schedule.len(), + procs.len() + ); + let (records_dir, proc_dir) = (out.join("records"), out.join("processes")); + for d in [&records_dir, &proc_dir] { + fs::create_dir_all(d).map_err(|e| format!("{}: {e}", d.display()))?; + } + let parent_env: Vec<(OsString, OsString)> = std::env::vars_os().collect(); + let sibling_at_start = sibling_idle(a.pin); + let machine_role = a + .machine_role + .clone() + .or_else(|| std::env::var("HOSTNAME").ok()) + .or_else(|| std::env::var("COMPUTERNAME").ok()) + .unwrap_or_else(|| "unknown".to_owned()); + let (rustc_version, triple) = rustc_info(); + + // equality phase: our tree against the C++ reference .out file, per tree, in fresh processes (the kernels are not touched by timing) + let eq_dir = out.join(format!("equality-b{:04}", a.batch)); + let mut equality: BTreeMap<&'static str, Outcome> = BTreeMap::new(); + for tree in &trees { + let p = Proc { imp: Impl::Rust, tree, rep: 'a' }; + let mut cmd = scrubbed_command(&own_exe, &parent_env, &cell_env(&p)); + cmd.arg("run-tree") + .arg(&a.dir) + .args(["--tree", tree, "--case", &a.case, "--out"]) + .arg(&eq_dir) + .args(["--pin", &a.pin.to_string()]); + run_cell(&mut cmd, &format!("{}/equality", p.name()))?; + let ours_name = format!("case-{}.rust-{tree}.out", a.case); + let ours = read_out(&eq_dir.join(&ours_name), &ours_name, case.rows, tree, None).map_err(|e| e.to_string())?; + let o = case.outs.iter().find(|o| o.tree == *tree).ok_or("missing reference out")?; + let reference = read_out(&a.dir.join(&o.name), &o.name, case.rows, tree, Some((&o.sha256, o.bytes))) + .map_err(|e| e.to_string())?; + let outcome = compare_bits(&ours, &reference, case.tolerance.as_ref()); + println!( + "EQUALITY {} [{tree}] {}{}", + a.case, + if outcome.equal() { "EQUAL" } else { "NOT_EQUAL" }, + outcome.first_mismatch.map_or(format!("; {} values", outcome.compared), |(i, x, y)| format!( + "; {} of {} values differ, first at {i}: ours {x:#010x} reference {y:#010x}, max abs error {:e}", + outcome.mismatches, outcome.compared, outcome.max_abs_error + )) + ); + equality.insert(tree, outcome); + } + + let mut cpu_model = String::new(); + let batch_json = |cpu_model: String, equality: &BTreeMap<&'static str, Outcome>| -> Result { + 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)) + )) + }; + + let expect = + Expect { manifest_sha: &verified.manifest_sha256, input_sha: &case.in_sha256, case: &a.case, pin: a.pin }; + let mut ctx = BatchCtx { + verified: &verified, + case: &case, + pin: a.pin, + machine_role: machine_role.clone(), + os: host_os(), + cpu_model: String::new(), + started_utc: started.clone(), + rust_tool: Tool { compiler: "rustc".to_owned(), version: rustc_version, triple, flags: ours_flags() }, + batch: a.batch, + equality: &equality, + }; + let mut written = Vec::new(); + for (round_no, order) in &schedule { + let mut done: Vec = Vec::new(); + for p in order { + let name = p.name(); + let file = proc_dir.join(format!("r{round_no:05}-{name}.json")); + let mut cmd = scrubbed_command(if p.imp == Impl::Cpp { &kab } else { &own_exe }, &parent_env, &cell_env(p)); + cmd.arg("time") + .args(["--run-dir"]) + .arg(&a.dir) + .args(["--case", &a.case, "--slices", &a.slices.to_string(), "--pin", &a.pin.to_string(), "--out"]) + .arg(&file); + if let Some(ms) = a.slice_ms { + cmd.args(["--slice-ms", &ms.to_string()]); + } + if let Some(b) = a.llc_bytes { + cmd.args(["--llc-bytes", &b.to_string()]); + } + let res = run_cell(&mut cmd, &name)?; + fs::write(file.with_extension("log"), [&res.stdout[..], &res.stderr[..]].concat()) + .map_err(|e| format!("{}: {e}", file.display()))?; + let bytes = fs::read(&file) + .map_err(|e| format!("cell {name}: its output {} was not written: {e}", file.display()))?; + done.push(parse_proc_json(p, &bytes, &expect)?); + } + if cpu_model.is_empty() { + cpu_model = done.iter().find_map(|d| d.cpu_model.clone()).unwrap_or_else(|| "unknown model".to_owned()); + ctx.cpu_model = cpu_model.clone(); + create_new_file( + &out.join(format!("batch-{:04}.json", a.batch)), + batch_json(cpu_model.clone(), &equality)?.as_bytes(), + )?; + } + for (name, json) in round_records(&ctx, *round_no, &done)? { + create_new_file(&records_dir.join(&name), json.as_bytes())?; + written.push(name); + } + println!("round {round_no} done: {}", order.iter().map(Proc::name).collect::>().join(" ")); + } println!( "ALTERNATE OK batch={} rounds={} records={} dir={}", a.batch, a.rounds, written.len(), - run.paths.records_dir().display() + records_dir.display() ); for (t, o) in &equality { println!("EQUALITY-SUMMARY {} {t} {}", a.case, if o.equal() { "EQUAL" } else { "NOT_EQUAL" }); @@ -27,25 +225,17 @@ pub(super) fn cmd_alternate(args: &[String]) -> Result { Ok(ExitCode::SUCCESS) } -/// The manifest entry of the case, or the error that names it. -fn find_case<'a>(verified: &'a Verified, id: &str) -> Result<&'a CaseEntry, String> { - verified.cases.iter().find(|c| c.id == id).ok_or_else(|| format!("case {id} is not in the manifest")) -} - // ------------------------------------------------------------------------------------------------ main 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_compare_fn.rs b/crates/native-cpu-expert/examples/kernel_ab/cmd_compare_fn.rs index 012c58eb..2028a952 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,37 +1,16 @@ -//! 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::*; -/// What `compare` knows once the directory is verified and the output directory is chosen. -struct ComparePlan<'a> { - opts: &'a Options, - verified: Verified, - out: PathBuf, - records: PathBuf, - exe: PathBuf, - parent_env: Vec<(OsString, OsString)>, - started: String, - machine_role: String, - rustc_version: String, - triple: String, -} - -/// How the process of one tree ended. -enum TreeRun { - /// It ran; these are the `REPORT` lines it printed. - Ran(Vec), - /// This host has no AVX-512 and the manifest says so: the tree is not run. - Skipped, - Failed, -} - pub(super) fn cmd_compare(dir: &Path, opts: &Options) -> Result { let started = now_utc(); - let verified = match verify_or_exit(dir) { + let verified = match verify_dir(dir) { Ok(v) => v, - Err(code) => return Ok(code), + Err(e) => { + println!("{e}"); + return Ok(ExitCode::from(if e.incomplete { 2 } else { 1 })); + } }; println!( "KAB1 directory verified: {} files, {} cases, manifest sha256 {}", @@ -39,189 +18,127 @@ pub(super) fn cmd_compare(dir: &Path, opts: &Options) -> Result = std::env::vars_os().collect(); - let machine_role = machine_role_of(opts.machine_role.as_deref()); - let (rustc_version, triple) = rustc_info(); - let plan = - ComparePlan { opts, verified, out, records, exe, parent_env, started, machine_role, rustc_version, triple }; - run_compare_trees(&plan) -} - -/// `/`: the default output directory next to the run directory. -pub(super) fn sibling_dir(dir: &Path, suffix: &str) -> PathBuf { - 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}{suffix}")) -} - -/// The output directory neither contains nor lies inside the run directory and is absent or empty. -fn require_fresh_out_dir(dir: &Path, out: &Path) -> Result<(), String> { - if out.starts_with(dir) || dir.starts_with(out) { - return Err("--out must not contain or lie inside the KAB1 directory".to_owned()); - } - if out.exists() && fs::read_dir(out).map_err(|e| format!("{}: {e}", out.display()))?.next().is_some() { - return Err(format!("{} exists and is not empty (nothing is overwritten or deleted)", out.display())); - } - Ok(()) -} - -/// The machine role: the given name, else the host name from the environment, else `unknown`. -pub(super) fn machine_role_of(given: Option<&str>) -> String { - given - .map(str::to_owned) + 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()) -} - -/// The tree with this name from `TREES` (`avx2` for a name that is not one). -fn static_tree(tree: &str) -> &'static str { - TREES.iter().find(|t| **t == tree).copied().unwrap_or("avx2") -} - -fn run_compare_trees(plan: &ComparePlan) -> Result { - let (mut all_equal, mut cells) = (true, 0usize); - for tree in &plan.opts.trees { - let sibling = sibling_idle(plan.opts.pin); - let report = match run_tree_process(plan, tree)? { - TreeRun::Ran(report) => report, - TreeRun::Skipped => continue, - TreeRun::Failed => return Ok(ExitCode::from(1)), + .unwrap_or_else(|| "unknown".to_owned()); + let (rustc_version, triple) = rustc_info(); + let flags = format!( + "cargo profile {}; RUSTFLAGS={:?}; target-cpu default", + if cfg!(debug_assertions) { "dev" } else { "release" }, + std::env::var("RUSTFLAGS").unwrap_or_default() + ); + let mut all_equal = true; + let mut cells = 0usize; + for tree in &opts.trees { + let sibling = sibling_idle(opts.pin); + let probe = Proc { + imp: Impl::Rust, + tree: TREES.iter().find(|t| **t == tree.as_str()).copied().unwrap_or("avx2"), + rep: 'a', }; + let mut cmd = scrubbed_command(&exe, &parent_env, &cell_env(&probe)); + cmd.arg("run-tree").arg(dir).args(["--tree", tree, "--out"]).arg(&out).args(["--pin", &opts.pin.to_string()]); + let res = cmd.output().map_err(|e| format!("cannot start the {tree} process: {e}"))?; + let stdout = String::from_utf8_lossy(&res.stdout).into_owned(); + let report: Vec = stdout.lines().filter_map(|l| l.strip_prefix("REPORT ")).map(str::to_owned).collect(); + match res.status.code() { + Some(0) => {} + Some(3) if tree == "avx512" && verified.provenance.avx512_ok == Some(false) => { + println!( + "tree avx512: SKIPPED, this host has no AVX-512 (manifest avx512_ok=false; the reference trees are identical by construction)" + ); + continue; + } + code => { + eprint!("{}", String::from_utf8_lossy(&res.stderr)); + println!("tree {tree}: the Rust process failed (exit {code:?})"); + return Ok(ExitCode::from(1)); + } + } println!( "tree {tree}: {}", report.iter().find(|l| l.starts_with("cpu: process kernel family")).map_or("", String::as_str) ); - for c in &plan.verified.cases { - all_equal &= compare_case(plan, tree, c, &report, sibling)?; + let tree_name: &str = TREES.iter().find(|t| **t == tree.as_str()).copied().unwrap_or("avx2"); + for c in &verified.cases { + let ours_name = format!("case-{}.rust-{tree}.out", c.id); + let ours = read_out(&out.join(&ours_name), &ours_name, c.rows, tree, None).map_err(|e| e.to_string())?; + let o = c.outs.iter().find(|o| o.tree == tree_name).ok_or("missing reference out")?; + let reference = read_out(&verified.dir.join(&o.name), &o.name, c.rows, tree, Some((&o.sha256, o.bytes))) + .map_err(|e| e.to_string())?; + let outcome = compare_bits(&ours, &reference, c.tolerance.as_ref()); + let label = match (&c.tolerance, outcome.equal()) { + (None, true) => "bitwise EQUAL".to_owned(), + (None, false) => "bitwise NOT EQUAL".to_owned(), + (Some(t), eq) => format!( + "{} within tolerance {:e} (metric {TOLERANCE_METRIC}; basis: {})", + if eq { "EQUAL" } else { "NOT EQUAL" }, + t.value, + t.basis + ), + }; + let detail = match outcome.first_mismatch { + Some((i, a, b)) => format!( + "; {} of {} values differ, first at {i}: ours {a:#010x} reference {b:#010x}, max abs error {:e}", + outcome.mismatches, outcome.compared, outcome.max_abs_error + ), + None => format!("; {} values", outcome.compared), + }; + println!("case {} [{tree}] {label}{detail}", c.id); + all_equal &= outcome.equal(); cells += 1; + let record = record_json(&RecordInput { + record_id: format!( + "kab1-{}-{}-{tree}-{}", + verified.provenance.run_id, + c.id, + started.replace([':', '-'], "") + ), + created_utc: now_utc(), + run_started_utc: started.clone(), + machine_role: machine_role.clone(), + cpu_model: cpu_model_of(&report), + os: host_os(), + ours_compiler: "rustc".to_owned(), + ours_version: rustc_version.clone(), + ours_triple: triple.clone(), + ours_flags: flags.clone(), + tree: tree_name, + verified: &verified, + case: c, + pin_cpu: opts.pin, + sibling_idle: sibling, + outcome: &outcome, + }); + let path = records.join(format!("case-{}.{tree}.record.json", c.id)); + fs::write(&path, record).map_err(|e| format!("{}: {e}", path.display()))?; } } println!( "compared {cells} cells; records in {}; {}", - plan.records.display(), + records.display(), if all_equal { "ALL EQUAL" } else { "NOT ALL EQUAL" } ); Ok(if all_equal && cells > 0 { ExitCode::SUCCESS } else { ExitCode::from(1) }) } -/// Runs `run-tree` for one tree in a fresh process and says how it ended; a skip or a failure is reported here. -fn run_tree_process(plan: &ComparePlan, tree: &str) -> Result { - let probe = Proc { imp: Impl::Rust, tree: static_tree(tree), rep: 'a' }; - let mut cmd = scrubbed_command(&plan.exe, &plan.parent_env, &cell_env(&probe)); - cmd.arg("run-tree").arg(&plan.verified.dir).args(["--tree", tree, "--out"]).arg(&plan.out); - cmd.args(["--pin", &plan.opts.pin.to_string()]); - let res = cmd.output().map_err(|e| format!("cannot start the {tree} process: {e}"))?; - let stdout = String::from_utf8_lossy(&res.stdout).into_owned(); - let report: Vec = stdout.lines().filter_map(|l| l.strip_prefix("REPORT ")).map(str::to_owned).collect(); - match res.status.code() { - Some(0) => Ok(TreeRun::Ran(report)), - Some(3) if tree == "avx512" && plan.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)" - ); - Ok(TreeRun::Skipped) - } - code => { - eprint!("{}", String::from_utf8_lossy(&res.stderr)); - println!("tree {tree}: the Rust process failed (exit {code:?})"); - Ok(TreeRun::Failed) - } - } -} - -/// Our output against the reference for one case: prints the verdict line, writes the record; true when equal. -fn compare_case( - plan: &ComparePlan, - tree: &str, - c: &CaseEntry, - report: &[String], - sibling: bool, -) -> Result { - let (ours, reference) = read_ours_and_reference(&plan.out, &plan.verified.dir, c, tree, static_tree(tree))?; - let outcome = compare_bits(&ours, &reference, c.tolerance.as_ref()); - println!("case {} [{tree}] {}{}", c.id, compare_label(c, &outcome), mismatch_detail(&outcome)); - let record = record_json(&compare_record_input(plan, tree, c, report, sibling, &outcome)); - let path = plan.records.join(format!("case-{}.{tree}.record.json", c.id)); - fs::write(&path, record).map_err(|e| format!("{}: {e}", path.display()))?; - Ok(outcome.equal()) -} - -/// Reads our `.out` file of the case from `ours_dir` and the C++ reference from `ref_dir` (checked against the -/// manifest). `lookup` names the tree whose reference file is taken. -pub(super) fn read_ours_and_reference( - ours_dir: &Path, - ref_dir: &Path, - c: &CaseEntry, - tree: &str, - lookup: &str, -) -> Result<(Vec, Vec), String> { - let ours_name = format!("case-{}.rust-{tree}.out", c.id); - let ours = read_out(&ours_dir.join(&ours_name), &ours_name, c.rows, tree, None).map_err(|e| e.to_string())?; - let o = c.outs.iter().find(|o| o.tree == lookup).ok_or("missing reference out")?; - let reference = read_out(&ref_dir.join(&o.name), &o.name, c.rows, tree, Some((&o.sha256, o.bytes))) - .map_err(|e| e.to_string())?; - Ok((ours, reference)) -} - -fn compare_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 - ), - } -} - -/// What differs, or how many values were compared when nothing does. -pub(super) fn mismatch_detail(o: &Outcome) -> String { - match o.first_mismatch { - Some((i, a, b)) => format!( - "; {} of {} values differ, first at {i}: ours {a:#010x} reference {b:#010x}, max abs error {:e}", - o.mismatches, o.compared, o.max_abs_error - ), - None => format!("; {} values", o.compared), - } -} - -fn compare_record_input<'a>( - plan: &'a ComparePlan, - tree: &str, - c: &'a CaseEntry, - report: &[String], - sibling: bool, - outcome: &'a Outcome, -) -> RecordInput<'a> { - let run_id = &plan.verified.provenance.run_id; - RecordInput { - record_id: format!("kab1-{run_id}-{}-{tree}-{}", c.id, plan.started.replace([':', '-'], "")), - created_utc: now_utc(), - run_started_utc: plan.started.clone(), - machine_role: plan.machine_role.clone(), - cpu_model: cpu_model_of(report), - os: host_os(), - ours_compiler: "rustc".to_owned(), - ours_version: plan.rustc_version.clone(), - ours_triple: plan.triple.clone(), - ours_flags: ours_flags(), - tree: static_tree(tree), - verified: &plan.verified, - case: c, - pin_cpu: plan.opts.pin, - sibling_idle: sibling, - outcome, - } -} - impl Flags { pub(super) fn parse(args: &[String], known: &[&str]) -> Result { let mut items: Vec<(String, String)> = Vec::new(); @@ -248,18 +165,6 @@ impl Flags { pub(super) fn number(&self, k: &str) -> Result, String> { self.get(k).map(|v| v.parse::().map_err(|_| format!("--{k} {v:?} is not a valid number"))).transpose() } - /// A number that must be given: `--k` missing is an error. - pub(super) fn need_number(&self, k: &str) -> Result { - self.number::(k)?.ok_or_else(|| format!("--{k} is required")) - } - /// The `--case` value, which must be a plain identifier. - pub(super) fn case_id(&self) -> Result { - let case = self.req("case")?.to_owned(); - if !valid_id(&case) { - return Err(format!("--case {case:?} is not a plain identifier")); - } - Ok(case) - } } pub(super) fn mono_ns() -> u64 { @@ -267,9 +172,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 ad9da167..e594ab1b 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,55 +3,245 @@ #[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. +/// `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 p = prepare_time_run(args)?; - let (pool, want) = first_call(&p.tc.case)?; + let t = parse_time_args(args)?; + let wall0 = mono_ns(); + // pin first (before any buffer or pool exists, so the pool's threads inherit the mask), then the facts about the pin + if rust_topology::pin_current_thread(t.pin as i32) < 0 { + return Err(format!("the pin to CPU {} was refused", t.pin)); + } + if cfg!(target_os = "linux") && current_cpu() != Some(t.pin) { + return Err(format!("the process is not running on CPU {} after the pin", t.pin)); + } + let cpu_dir = format!("/sys/devices/system/cpu/cpu{}", t.pin); + let sib_text = read_text(&format!("{cpu_dir}/topology/thread_siblings_list")); + let sibling = parse_cpu_list(&sib_text).into_iter().rfind(|c| *c != t.pin); + let sib0 = sibling.and_then(proc_stat_cpu); + let pin0 = proc_stat_cpu(t.pin); + let load0 = read_text("/proc/loadavg"); + + // the case: the KAB1 reader rule (validate, then use) and the manifest and case input hashes + let (manifest_bytes, _provenance, cases, _files) = read_manifest(&t.dir).map_err(|e| e.to_string())?; + let manifest_sha = sha_hex(&manifest_bytes); + let entry = + cases.iter().find(|c| c.id == t.case).ok_or_else(|| format!("case {} is not in the manifest", t.case))?; + let case = read_case_in(&t.dir, entry).map_err(|e| e.to_string())?; + let header = case.header; + let weights = &case.blob[IN_HEADER..header.input_at()]; + let expert_bytes = weights.len(); + + // environment and tree + let env = managed_env_now(); + let report = cpu_kernel_report(); + let tree = family_of(&report).ok_or("no process kernel family line in cpu_kernel_report")?; + + // the streamed set: K copies, K x stride at least 2 x the last-level cache of the pinned CPU (the design choice of kab_time.cpp) + let llc = match (t.llc_bytes, llc_of_cpu(t.pin)) { + (Some(bytes), found) => { + Llc { level: found.map_or(0, |l| l.level), bytes, source: "--llc-bytes (override)".to_owned() } + } + (None, Some(l)) => l, + (None, None) => { + return Err(format!("cannot read the last-level cache size of CPU {} from sysfs; pass --llc-bytes", t.pin)); + } + }; + if llc.bytes == 0 { + return Err("--llc-bytes must be positive".to_owned()); + } + let stride = expert_bytes.div_ceil(ALIGN) * ALIGN; + let copies_k = ((2 * llc.bytes) / stride as u64) as usize + 1; + if copies_k * stride > (4usize << 30) { + return Err("the streamed working set would exceed 4 GiB; check --llc-bytes".to_owned()); + } + + // the pool is created AFTER the pin: its worker inherits the one-CPU mask (rust_platform::cores sees a one-CPU affinity) + let mut pool = DirectCpuPool::new(1).map_err(|e| format!("DirectCpuPool::new(1) failed: {e:?}"))?; + let want = compute_case(&mut pool, &case)?; let want_bits: Vec = want.iter().map(|v| v.to_bits()).collect(); let output_sha = f32_bits_sha(&want); - let buffers = fill_buffers(&p.tc.case, &p.plan); - let copies = buffers.copies(&p.plan); - let mut timed = buffers.timed(pool, p.tc.case.header)?; - let m = measure(&p.t, &p.plan, &mut timed, &copies, &want_bits)?; - let end = read_pin_end(&p.start, p.t.pin); - let report = TimeReport { p: &p, end: &end, m: &m, output_sha: &output_sha }; - write_time_json(&p.t.out, &render_time_json(&report))?; - print_time_summary(&p, &m); - Ok(time_exit_code(&p.t, &m)) -} -fn print_time_summary(p: &Prepared, m: &Measured) { - println!( - "kernel_ab time: case={} tree={} pin={} slices={} resident_kept={} streamed_kept={} K={} out={}", - p.t.case, - p.tree, - p.t.pin, - p.t.slices, - m.regimes.kept_res, - m.regimes.kept_stm, - p.plan.copies_k, - p.t.out.display() + 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); + } + let res_copies: Vec<&[u8]> = vec![resident.slice(expert_bytes)]; + let stm_all = streamed.slice(stride * copies_k); + let stm_copies: Vec<&[u8]> = (0..copies_k).map(|k| &stm_all[k * stride..k * stride + expert_bytes]).collect(); + + let mut timed = Timed { + pool, + gu: gate_up_row(header.gu).ok_or("gate/up type")?.1, + down: down_row(header.down).ok_or("down type")?.1, + header, + pairs: (0..header.rows).map(|r| (r, 0)).collect(), + tokens: tokens.slice(header.rows * H), + out: vec![0.0f32; header.rows * H], + }; + // selfcheck: the timed call's output on every aligned copy is bit-identical to the first (unaligned) call's + let mut selfcheck = true; + for w in [res_copies[0], stm_copies[0], stm_copies[copies_k - 1]] { + timed.call(w)?; + selfcheck &= timed.out.iter().map(|v| v.to_bits()).eq(want_bits.iter().copied()); + } + if !selfcheck { + return Err("selfcheck failed: the timed call differs from the first call".to_owned()); + } + + let ghz0 = core_ghz(); + let mut regimes = Vec::new(); + let mut all_ok = true; + let (mut kept_res, mut kept_stm) = (0, 0); + for (label, copies, sel) in + [("RESIDENT", &res_copies, RegimeSel::Resident), ("STREAMED", &stm_copies, RegimeSel::Streamed)] + { + if t.regime != RegimeSel::Both && t.regime != sel { + continue; + } + let spec = RegimeSpec { + label, + copies: copies.clone(), + expert_bytes, + stride, + llc: &llc, + slices: t.slices, + slice_ms: t.slice_ms, + pin: t.pin, + selfcheck, + }; + let r = run_regime(&mut timed, &spec)?; + all_ok &= r.ok; + if sel == RegimeSel::Resident { + kept_res = r.kept + } else { + kept_stm = r.kept + } + regimes.push(r.json); + } + let ghz1 = core_ghz(); + timed.call(res_copies[0])?; + let final_same = timed.out.iter().map(|v| v.to_bits()).eq(want_bits.iter().copied()); + + let threads = observed_threads(); + let sib1 = sibling.and_then(proc_stat_cpu); + let pin1 = proc_stat_cpu(t.pin); + let frac = |f: Option| 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(), + } ); -} - -/// Writes the JSON to `.tmp` and renames it over `out`. -fn write_time_json(out: &Path, json: &str) -> Result<(), String> { - let tmp = PathBuf::from(format!("{}.tmp", out.display())); - fs::write(&tmp, json.as_bytes()).map_err(|e| format!("{}: {e}", tmp.display()))?; - fs::rename(&tmp, out).map_err(|e| format!("rename to {}: {e}", out.display())) -} - -/// 3 when a regime kept no slice or a slice migrated off the pin; 4 when the final output differs; else 0. -fn time_exit_code(t: &TimeArgs, m: &Measured) -> ExitCode { - if !m.regimes.all_ok { + 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 ExitCode::from(3); + return Ok(ExitCode::from(3)); } - if !m.final_same { + if !final_same { eprintln!("kernel_ab time: the final output differs from the first call's"); - return ExitCode::from(4); + return Ok(ExitCode::from(4)); } - ExitCode::SUCCESS + Ok(ExitCode::SUCCESS) } diff --git a/crates/native-cpu-expert/examples/kernel_ab/command_dispatch.rs b/crates/native-cpu-expert/examples/kernel_ab/command_dispatch.rs deleted file mode 100644 index a7c94f8b..00000000 --- a/crates/native-cpu-expert/examples/kernel_ab/command_dispatch.rs +++ /dev/null @@ -1,49 +0,0 @@ -//! The command table of `kernel_ab`: which command line runs which command, and how a refusal of the directory ends -//! one. - -#[allow(unused_imports)] -use super::*; - -/// `time` and `alternate`: flags only (the command line of `kab time`); a failure is printed with the command's name. -pub(super) fn run_flag_command(cmd: &str, args: &[String]) -> ExitCode { - let result = if cmd == "time" { cmd_time(args) } else { cmd_alternate(args) }; - result.unwrap_or_else(|e| { - eprintln!("kernel_ab {cmd}: {e}"); - ExitCode::from(1) - }) -} - -/// `verify`, `compare` and `run-tree`, which take the directory first; None when the command line is not one of them. -pub(super) fn run_dir_command(cmd: &str, dir: &Path, opts: &Options) -> Option { - let result = match cmd { - "verify" => cmd_verify(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()), - _ => return None, - }, - _ => return None, - }; - Some(result.unwrap_or_else(|e| { - eprintln!("kernel_ab: {e}"); - ExitCode::from(1) - })) -} - -/// The directory verified, or the exit code of its refusal (2: incomplete, 1: refused) after the refusal is printed. -pub(super) fn verify_or_exit(dir: &Path) -> Result { - verify_dir(dir).map_err(|e| { - println!("{e}"); - ExitCode::from(if e.incomplete { 2 } else { 1 }) - }) -} - -fn cmd_verify(dir: &Path) -> Result { - Ok(match verify_or_exit(dir) { - Ok(v) => { - println!("OK {} files (manifest sha256 {})", v.file_count, v.manifest_sha256); - ExitCode::SUCCESS - } - Err(code) => code, - }) -} 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 c53fa818..b291242b 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,5 +1,4 @@ -//! 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::*; @@ -29,156 +28,102 @@ 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(); - read_proc_cell(p, &j, expect).map_err(|what| format!("cell {name}: {what}")) -} - -/// The checks and the reading of a parsed process JSON; a failure carries no cell name yet. -fn read_proc_cell(p: &Proc, j: &Json, expect: &Expect) -> Result { - require_cell_run(j, p, expect)?; - let regimes = parse_regimes(j, p.imp)?; - let clock = j.req("clock_calibration")?; - let sibling_idle = read_sibling_idle(j)?; - let (tree_text, cpu_report) = read_tree_text(j, p)?; + let fail = |what: String| format!("cell {name}: {what}"); + if j.str("format").map_err(fail)? != "KAB1-time" || j.uint("version").map_err(fail)? != 1 { + return Err(fail("the output is not KAB1-time version 1".to_owned())); + } + if j.str("writer").map_err(fail)? != p.imp.name() { + return Err(fail(format!( + "the output's writer is {:?}, expected {}", + j.str("writer").unwrap_or("?"), + p.imp.name() + ))); + } + if j.str("tree").map_err(fail)? != p.tree { + return Err(fail(format!( + "the process ran the {} tree, the cell asks for {}", + j.str("tree").unwrap_or("?"), + p.tree + ))); + } + if j.str("manifest_sha256").map_err(fail)? != expect.manifest_sha { + return Err(fail("manifest_sha256 differs from the run directory's".to_owned())); + } + let c = j.req("case").map_err(fail)?; + if c.str("id").map_err(fail)? != expect.case || c.str("input_sha256").map_err(fail)? != expect.input_sha { + return Err(fail("the case id or its input hash differs from the manifest's".to_owned())); + } + let pin = j.req("pin").map_err(fail)?; + if pin.uint("cpu").map_err(fail)? as usize != expect.pin { + return Err(fail(format!("pinned to CPU {}, expected {}", pin.uint("cpu").unwrap_or(u64::MAX), expect.pin))); + } + let want_env: BTreeMap = cell_env(p).into_iter().collect(); + let mut seen_env = BTreeMap::new(); + if let Json::Obj(items) = j.req("effective_env").map_err(fail)? { + for (k, v) in items { + seen_env.insert( + k.clone(), + match v { + Json::Str(s) => s.clone(), + Json::Num(n) => n.clone(), + _ => "?".to_owned(), + }, + ); + } + } + if seen_env != want_env { + return Err(fail(format!("effective environment {seen_env:?} differs from the cell's {want_env:?}"))); + } + let mut regimes = BTreeMap::new(); + for r in j.array("regimes").map_err(fail)? { + let label = r.str("regime").map_err(fail)?.to_owned(); + regimes.insert(label, parse_regime(r, p.imp).map_err(fail)?); + } + for want in ["RESIDENT", "STREAMED"] { + if !regimes.contains_key(want) { + return Err(fail(format!("regime {want} is missing"))); + } + } + let clock = j.req("clock_calibration").map_err(fail)?; + let sibling_idle = match pin.req("sibling_cpu").map_err(fail)? { + Json::Null => Some(true), + _ => pin.float_or_null("sibling_busy_fraction_during_run").map_err(fail)?.map(|f| f < SIBLING_BUSY_LIMIT), + }; + let detail = j.req("tree_detail").map_err(fail)?; + let (tree_text, cpu_report) = if p.imp == Impl::Rust { + let report: Vec = 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")?, - ghz_end: clock.float("ghz_at_end")?, + 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")?, + 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, }) } - -/// The process says it is the run that was asked for: format, writer, tree, manifest, case, pin and environment. -fn require_cell_run(j: &Json, p: &Proc, expect: &Expect) -> Result<(), String> { - require_time_format(j)?; - require_writer(j, p)?; - require_tree(j, p)?; - require_manifest_sha(j, expect)?; - require_case(j, expect)?; - require_pin(j, expect)?; - require_cell_env(j, p) -} - -fn require_time_format(j: &Json) -> Result<(), String> { - if j.str("format")? != "KAB1-time" || j.uint("version")? != 1 { - return Err("the output is not KAB1-time version 1".to_owned()); - } - Ok(()) -} - -fn require_writer(j: &Json, p: &Proc) -> Result<(), String> { - if j.str("writer")? != p.imp.name() { - return Err(format!("the output's writer is {:?}, expected {}", j.str("writer").unwrap_or("?"), p.imp.name())); - } - Ok(()) -} - -fn require_tree(j: &Json, p: &Proc) -> Result<(), String> { - 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)); - } - Ok(()) -} - -fn require_manifest_sha(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()); - } - Ok(()) -} - -fn require_case(j: &Json, expect: &Expect) -> Result<(), String> { - 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()); - } - Ok(()) -} - -fn require_pin(j: &Json, expect: &Expect) -> Result<(), 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)); - } - Ok(()) -} - -/// The environment the process reports is exactly the cell's. -fn require_cell_env(j: &Json, p: &Proc) -> Result<(), String> { - let want_env: BTreeMap = cell_env(p).into_iter().collect(); - let mut seen_env = BTreeMap::new(); - if let Json::Obj(items) = j.req("effective_env")? { - for (k, v) in items { - seen_env.insert(k.clone(), env_value_text(v)); - } - } - if seen_env != want_env { - return Err(format!("effective environment {seen_env:?} differs from the cell's {want_env:?}")); - } - Ok(()) -} - -fn env_value_text(v: &Json) -> String { - match v { - Json::Str(s) => s.clone(), - Json::Num(n) => n.clone(), - _ => "?".to_owned(), - } -} - -/// Both regimes of the process by label; a missing RESIDENT or STREAMED is an error. -fn parse_regimes(j: &Json, imp: Impl) -> Result, String> { - let mut regimes = BTreeMap::new(); - for r in j.array("regimes")? { - let label = r.str("regime")?.to_owned(); - regimes.insert(label, parse_regime(r, imp)?); - } - for want in ["RESIDENT", "STREAMED"] { - if !regimes.contains_key(want) { - return Err(format!("regime {want} is missing")); - } - } - Ok(regimes) -} - -/// Whether the SMT sibling stayed idle; unknown (None) when the sibling's busy fraction is null. -fn read_sibling_idle(j: &Json) -> Result, String> { - let pin = j.req("pin")?; - Ok(match pin.req("sibling_cpu")? { - Json::Null => Some(true), - _ => pin.float_or_null("sibling_busy_fraction_during_run")?.map(|f| f < SIBLING_BUSY_LIMIT), - }) -} - -/// The text that describes the tree of the process, and (Rust only) the report lines it printed. -fn read_tree_text(j: &Json, p: &Proc) -> Result<(String, Vec), String> { - let detail = j.req("tree_detail")?; - if p.imp != Impl::Rust { - return Ok((describe_cpp_tree(detail), Vec::new())); - } - 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 { @@ -222,8 +167,7 @@ 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, @@ -231,9 +175,8 @@ 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 a6a7a703..cf075fd3 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,5 +1,4 @@ -//! 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 d4fb7e71..a50737c4 100644 --- a/crates/native-cpu-expert/examples/kernel_ab/impl_impl.rs +++ b/crates/native-cpu-expert/examples/kernel_ab/impl_impl.rs @@ -1,5 +1,4 @@ -//! 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::*; @@ -47,11 +46,10 @@ 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" { @@ -65,8 +63,7 @@ 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)], @@ -118,9 +115,8 @@ 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(); @@ -155,8 +151,7 @@ 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(",")); @@ -164,8 +159,7 @@ 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)) { @@ -173,9 +167,16 @@ 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, order) = parse_schedule_line(l)?; + 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::>()?; if let Some(prev) = rounds.last() - && !follows_round(prev, no, &order) + && (no != prev.0 + 1 + || BTreeSet::from_iter(order.iter()) != BTreeSet::from_iter(prev.1.iter()) + || order.len() != prev.1.len()) { return Err(format!("round {no} does not follow round {} with the same processes", prev.0)); } @@ -187,123 +188,45 @@ pub(super) fn parse_schedule(text: &str) -> Result)>, String Ok(rounds) } -/// One schedule line: the round number, a tab, the process names separated by commas. -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)) -} - -/// Whether round `no` with `order` is the round after `prev` and names the same processes. -fn follows_round(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()) } -/// The kept slices of one regime and the largest clock drift over the kept and the dropped slices. -struct Samples { - ns: Vec, - cycles: Vec, - max_drift: f64, -} - -/// One slice of the process JSON: its clock before and after and, for a kept slice, its time per call. -struct SliceSample { - ghz_before: f64, - ghz_after: f64, - kept: Option<(f64, f64)>, -} - -fn parse_slice(s: &Json, keep: bool) -> Result { - let (ghz_before, ghz_after) = (s.float("ghz_before")?, s.float("ghz_after")?); - let kept = if keep { Some((s.float("ns_per_call")?, s.float("cycles_per_call")?)) } else { None }; - Ok(SliceSample { ghz_before, ghz_after, kept }) -} - -fn read_samples(r: &Json) -> Result { - let mut samples = Samples { ns: Vec::new(), cycles: Vec::new(), max_drift: 0.0f64 }; +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; for (key, keep) in [("slices", true), ("dropped", false)] { for s in r.array(key)? { - let slice = parse_slice(s, keep)?; - samples.add_slice(&slice); + 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")?); + } } } - Ok(samples) -} - -impl Samples { - fn add_slice(&mut self, s: &SliceSample) { - let (g0, g1) = (s.ghz_before, s.ghz_after); - if g0 > 0.0 { - self.max_drift = self.max_drift.max(((g1 - g0).abs() / g0).min(1.0)); - } - if let Some((ns, cycles)) = s.kept { - self.ns.push(ns); - self.cycles.push(cycles); - } - } -} - -pub(super) fn parse_regime(r: &Json, imp: Impl) -> Result { - let Samples { ns, cycles, max_drift } = read_samples(r)?; - require_kept_count(r, ns.len())?; - let sets = read_set_counts(r)?; - Ok(RegimeStat { - copies_k: sets.copies_k, - expert_bytes: sets.expert_bytes, - llc_bytes: sets.llc_bytes, - requested: sets.requested, - dropped: sets.dropped, - median_ns: r.float("median_ns_per_call")?, - median_cycles: r.float("median_cycles_per_call")?, - ns, - cycles, - max_drift, - selfcheck: r.flag(selfcheck_key(imp))?, - }) -} - -/// The JSON key of the regime's selfcheck verdict: the C++ driver compares with `compose_expert()`, ours with the first -/// call. -fn selfcheck_key(imp: Impl) -> &'static str { - if imp == Impl::Cpp { "selfcheck_bitwise_equal_compose_expert" } else { "selfcheck_bitwise_equal_first_call" } -} - -/// `slices_kept` agrees with the kept slices that were read, and at least one was kept. -fn require_kept_count(r: &Json, read: usize) -> Result<(), String> { + 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 != read || kept == 0 { - return Err(format!("slices_kept {kept} disagrees with the {read} kept slices (or none was kept)")); + if kept != ns.len() || kept == 0 { + return Err(format!("slices_kept {kept} disagrees with the {} kept slices (or none was kept)", ns.len())); } - Ok(()) -} - -/// The counts a regime reports about its set of copies and its slices. -struct SetCounts { - copies_k: usize, - expert_bytes: usize, - llc_bytes: u64, - requested: usize, - dropped: usize, -} - -fn read_set_counts(r: &Json) -> Result { - Ok(SetCounts { + Ok(RegimeStat { copies_k: r.uint("copies_k")? as usize, expert_bytes: r.uint("expert_bytes")? as usize, llc_bytes: r.uint("llc_bytes")?, requested: r.uint("slices_requested")? as usize, dropped: r.uint("dropped_count")? as usize, + median_ns: r.float("median_ns_per_call")?, + median_cycles: r.float("median_cycles_per_call")?, + ns, + cycles, + max_drift, + selfcheck: r.flag(selfcheck_key)?, }) } 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 d41568ef..8c356062 100644 --- a/crates/native-cpu-expert/examples/kernel_ab/impl_parser.rs +++ b/crates/native-cpu-expert/examples/kernel_ab/impl_parser.rs @@ -38,7 +38,39 @@ impl Parser<'_> { match c { b'"' => return String::from_utf8(out).map_err(|_| "string is not UTF-8".to_owned()), b'\\' => { - let ch = self.escape()?; + let Some(&e) = self.b.get(self.at) else { return self.err("unterminated escape") }; + self.at += 1; + let ch = match e { + b'"' => '"', + b'\\' => '\\', + b'/' => '/', + b'b' => '\u{8}', + b'f' => '\u{c}', + b'n' => '\n', + b'r' => '\r', + b't' => '\t', + b'u' => { + let hi = self.hex4()?; + let cp = if (0xD800..0xDC00).contains(&hi) { + if !self.b[self.at..].starts_with(b"\\u") { + return self.err("lone surrogate"); + } + self.at += 2; + let lo = self.hex4()?; + if !(0xDC00..0xE000).contains(&lo) { + return self.err("lone surrogate"); + } + 0x10000 + ((hi - 0xD800) << 10) + (lo - 0xDC00) + } else { + hi + }; + match char::from_u32(cp) { + Some(c) => c, + None => return self.err("lone surrogate"), + } + } + _ => return self.err("unknown escape"), + }; let mut buf = [0u8; 4]; out.extend_from_slice(ch.encode_utf8(&mut buf).as_bytes()); } @@ -47,39 +79,6 @@ impl Parser<'_> { } } } - /// The character an escape sequence stands for; the backslash is already consumed. - 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"), - } - } - /// `\uXXXX`, with the low half of a surrogate pair when the first half asks for one; the `u` is already consumed. - 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 the pair whose high half is `hi`; the low half must follow as `\uXXXX`. - 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') { @@ -98,102 +97,70 @@ impl Parser<'_> { self.ws(); match self.b.get(self.at) { None => self.err("unexpected end"), - Some(b'{') => self.object(depth), - Some(b'[') => self.array(depth), - Some(b'"') => self.string().map(Json::Str), - Some(b't' | b'f' | b'n') => self.keyword(), + Some(b'{') => { + self.at += 1; + let mut items: Vec<(String, Json)> = Vec::new(); + self.ws(); + if self.b.get(self.at) == Some(&b'}') { + self.at += 1; + return Ok(Json::Obj(items)); + } + loop { + self.ws(); + if self.b.get(self.at) != Some(&b'"') { + return self.err("object key expected"); + } + let key = self.string()?; + if items.iter().any(|(k, _)| *k == key) { + return self.err(&format!("duplicate key {key:?}")); + } + self.ws(); + if self.b.get(self.at) != Some(&b':') { + return self.err("':' expected"); + } + self.at += 1; + let v = self.value(depth + 1)?; + items.push((key, v)); + self.ws(); + match self.b.get(self.at) { + Some(b',') => self.at += 1, + Some(b'}') => { + self.at += 1; + return Ok(Json::Obj(items)); + } + _ => return self.err("',' or '}' expected"), + } + } + } + Some(b'[') => { + self.at += 1; + let mut items = Vec::new(); + self.ws(); + if self.b.get(self.at) == Some(&b']') { + self.at += 1; + return Ok(Json::Arr(items)); + } + loop { + items.push(self.value(depth + 1)?); + self.ws(); + match self.b.get(self.at) { + Some(b',') => self.at += 1, + Some(b']') => { + self.at += 1; + return Ok(Json::Arr(items)); + } + _ => return self.err("',' or ']' expected"), + } + } + } + Some(b'"') => Ok(Json::Str(self.string()?)), + Some(b't') => self.lit("true", Json::Bool(true)), + Some(b'f') => self.lit("false", Json::Bool(false)), + Some(b'n') => self.lit("null", Json::Null), Some(b'-' | b'0'..=b'9') => self.number(), Some(_) => self.err("unexpected character"), } } - /// `true`, `false` or `null`; the current byte is the first letter of one of them. - fn keyword(&mut self) -> Result { - match self.b[self.at] { - b't' => self.lit("true", Json::Bool(true)), - b'f' => self.lit("false", Json::Bool(false)), - _ => self.lit("null", Json::Null), - } - } - 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(depth, &items)?; - items.push(member); - self.ws(); - if self.end_of_item(b'}')? { - return Ok(Json::Obj(items)); - } - } - } - /// One `"key": value` of an object whose earlier members are `items`. - fn member(&mut self, depth: usize, items: &[(String, Json)]) -> 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)?); - self.ws(); - if self.end_of_item(b']')? { - return Ok(Json::Arr(items)); - } - } - } - /// After an item: a comma (false: more follow) or the closing byte (true); anything else is an error. - fn end_of_item(&mut self, close: u8) -> Result { - 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(&format!("',' or '{}' expected", close as char)), - } - } -} - -/// The character of a single-letter escape (`\n`, `\"`, ...); `u` is handled by the caller. -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 d00713b4..dbaa205d 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,9 +15,8 @@ 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"]; @@ -174,25 +173,23 @@ 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 = "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, @@ -200,7 +197,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 ff2d2ede..0153266e 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,11 +1,9 @@ -//! 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 { @@ -84,41 +82,25 @@ 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.need_number::("slices")?; - let pin = f.need_number::("pin")?; + 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); - require_time_ranges(slices, slice_ms)?; - let regime = parse_regime_sel(f.get("regime").unwrap_or("both"))?; - let case = f.case_id()?; - build_time_args(&f, (slices, pin, slice_ms), regime, case) -} - -fn require_time_ranges(slices: usize, slice_ms: f64) -> Result<(), String> { 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(()) -} - -fn parse_regime_sel(text: &str) -> Result { - match text { - "both" => Ok(RegimeSel::Both), - "resident" => Ok(RegimeSel::Resident), - "streamed" => Ok(RegimeSel::Streamed), - _ => Err("--regime must be both, resident or streamed".to_owned()), + let regime = match f.get("regime").unwrap_or("both") { + "both" => RegimeSel::Both, + "resident" => RegimeSel::Resident, + "streamed" => RegimeSel::Streamed, + _ => return Err("--regime must be both, resident or streamed".to_owned()), + }; + let case = f.req("case")?.to_owned(); + if !valid_id(&case) { + return Err(format!("--case {case:?} is not a plain identifier")); } -} - -/// The parsed command line from the values read so far and the paths and the cache override still to be read. -fn build_time_args( - f: &Flags, - (slices, pin, slice_ms): (usize, usize, f64), - regime: RegimeSel, - case: String, -) -> Result { Ok(TimeArgs { dir: PathBuf::from(f.req("run-dir")?), case, @@ -130,7 +112,6 @@ fn build_time_args( llc_bytes: f.number::("llc-bytes")?, }) } - impl Arena { pub(super) fn new(len: usize) -> Self { let size = std::mem::size_of::(); @@ -164,8 +145,7 @@ 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; @@ -197,8 +177,7 @@ 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 e6505982..0242a9e3 100644 --- a/crates/native-cpu-expert/examples/kernel_ab/main.rs +++ b/crates/native-cpu-expert/examples/kernel_ab/main.rs @@ -1,43 +1,35 @@ #![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 @@ -61,12 +53,16 @@ thread_local! { static BUFFERS: Cell = const { Cell::new(0) }; } 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 + // `time` and `alternate` take flags only (the command line of `kab time`); the older commands take the directory first if let Some(cmd @ ("time" | "alternate")) = args.first().map(String::as_str) { - return run_flag_command(cmd, &args[1..]); + let result = if cmd == "time" { cmd_time(&args[1..]) } else { cmd_alternate(&args[1..]) }; + return result.unwrap_or_else(|e| { + eprintln!("kernel_ab {cmd}: {e}"); + ExitCode::from(1) + }); } let (Some(cmd), Some(dir)) = (args.first(), args.get(1)) else { return usage() }; + let dir = Path::new(dir); let opts = match parse_options(&args[2..]) { Ok(o) => o, Err(e) => { @@ -74,7 +70,28 @@ fn main() -> ExitCode { return usage(); } }; - run_dir_command(cmd, Path::new(dir), &opts).unwrap_or_else(usage) + let result = match cmd.as_str() { + "verify" => match verify_dir(dir) { + Ok(v) => { + println!("OK {} files (manifest sha256 {})", v.file_count, v.manifest_sha256); + Ok(ExitCode::SUCCESS) + } + Err(e) => { + println!("{e}"); + Ok(ExitCode::from(if e.incomplete { 2 } else { 1 })) + } + }, + "compare" => cmd_compare(dir, &opts), + "run-tree" => match (&opts.tree, &opts.out) { + (Some(t), Some(o)) => cmd_run_tree(dir, t, o, opts.pin, opts.case.as_deref()), + _ => return usage(), + }, + _ => return usage(), + }; + result.unwrap_or_else(|e| { + eprintln!("kernel_ab: {e}"); + ExitCode::from(1) + }) } // ------------------------------------------------------------------------------------------------ tests @@ -174,8 +191,6 @@ use cmd_compare_fn::parse_size; use cmd_compare_fn::percentile_of; #[allow(unused_imports)] use cmd_compare_fn::read_text; -#[allow(unused_imports)] -use cmd_compare_fn::{machine_role_of, mismatch_detail, read_ours_and_reference, sibling_dir}; mod llc_of_cpu_fn; #[allow(unused_imports)] use llc_of_cpu_fn::busy_fraction; @@ -262,22 +277,6 @@ use cmd_alternate_fn::cmd_alternate; #[allow(unused_imports)] use cmd_alternate_fn::usage; -mod command_dispatch; -#[allow(unused_imports)] -use command_dispatch::{run_dir_command, run_flag_command, verify_or_exit}; -mod alternate_run; -#[allow(unused_imports)] -use alternate_run::{AltRun, prepare_alt_run, run_equality_phase, run_rounds}; -mod batch_json; -#[allow(unused_imports)] -use batch_json::batch_json; -mod time_session; -#[allow(unused_imports)] -use time_session::{Measured, PinEnd, Prepared, fill_buffers, first_call, measure, prepare_time_run, read_pin_end}; -mod time_report; -#[allow(unused_imports)] -use time_report::{TimeReport, render_time_json}; - mod in_magic_types; #[allow(unused_imports)] use in_magic_types::ALIGN; 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 0d5cff89..78c03831 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,105 +1,44 @@ -//! 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::*; -/// Opens `path` and returns the file with its length; `name` is what a refusal calls the file. -fn open_measured(path: &Path, name: &str) -> Result<(File, u64), Refusal> { - let f = File::open(path).map_err(|e| Refusal::new(name, format!("cannot open: {e}")))?; - let len = f.metadata().map_err(|e| Refusal::new(name, format!("cannot stat: {e}")))?.len(); - Ok((f, len)) -} - -/// The length is at most the limit and holds at least the header. -fn require_length_in_range(name: &str, len: u64, header: usize) -> Result<(), Refusal> { - if len > MAX_FILE_BYTES || len < header as u64 { - return Err(Refusal::new(name, format!("length {len} outside {header}..={MAX_FILE_BYTES}"))); - } - Ok(()) -} - -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 whose first bytes are the header that was already read. -fn read_whole(f: &mut File, name: &str, len: u64, hdr: &[u8]) -> Result, Refusal> { - let mut blob = take_buffer(len as usize).map_err(|reason| Refusal::new(name, reason))?; - blob[..hdr.len()].copy_from_slice(hdr); - f.read_exact(&mut blob[hdr.len()..]).map_err(|e| Refusal::new(name, format!("cannot read the body: {e}")))?; - Ok(blob) -} - -/// 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. +/// 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 (mut f, len) = open_measured(&dir.join(name), name)?; - require_manifest_length(name, len, c.in_bytes)?; - require_length_in_range(name, len, IN_HEADER)?; - let hdr = read_header::(&mut f, name)?; - let header = validate_in_header(&hdr, len).map_err(|reason| Refusal::new(name, reason))?; - require_header_matches(name, &header, c)?; - let blob = read_whole(&mut f, name, len, &hdr)?; - require_sha(name, &blob, &c.in_sha256)?; - let case = CaseIn { header, blob }; - require_finite_input(name, &case)?; - Ok(case) -} - -fn require_manifest_length(name: &str, len: u64, manifest_bytes: u64) -> Result<(), Refusal> { - if len != manifest_bytes { - return Err(Refusal::new(name, format!("length {len} differs from the manifest's {manifest_bytes}"))); + let r = |reason: String| Refusal::new(name, reason); + let mut f = File::open(dir.join(name)).map_err(|e| r(format!("cannot open: {e}")))?; + let len = f.metadata().map_err(|e| r(format!("cannot stat: {e}")))?.len(); + if len != c.in_bytes { + return Err(r(format!("length {len} differs from the manifest's {}", c.in_bytes))); } - Ok(()) -} - -/// The length is the manifest's, when the manifest has an entry for the file. -fn require_expected_length(name: &str, len: u64, expect: Option<(&str, u64)>) -> Result<(), Refusal> { - match expect { - Some((_, bytes)) => require_manifest_length(name, len, bytes), - None => Ok(()), + if len > MAX_FILE_BYTES || len < IN_HEADER as u64 { + return Err(r(format!("length {len} outside {IN_HEADER}..={MAX_FILE_BYTES}"))); } -} - -/// The hash is the manifest's, when the manifest has an entry for the file. -fn require_expected_sha(name: &str, blob: &[u8], expect: Option<(&str, u64)>) -> Result<(), Refusal> { - match expect { - Some((sha, _)) => require_sha(name, blob, sha), - None => Ok(()), - } -} - -fn require_header_matches(name: &str, header: &InHeader, c: &CaseEntry) -> Result<(), Refusal> { + 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(Refusal::new(name, "the header's types / rows differ from the manifest case")); + return Err(r("the header's types / rows differ from the manifest case".to_owned())); } - Ok(()) -} - -fn require_sha(name: &str, blob: &[u8], want: &str) -> Result<(), Refusal> { - if sha_hex(blob) != want { - return Err(Refusal::new(name, "sha256 differs from the manifest")); + 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())); } - Ok(()) -} - -/// Every FP16 block header of the weights and every activation of the case is finite. -fn require_finite_input(name: &str, case: &CaseIn) -> Result<(), Refusal> { - let header = case.header; + let case = CaseIn { header, blob }; let (gb, db) = (gate_up_row(header.gu).map_or(1, |x| x.3), down_row(header.down).map_or(1, |x| x.3)); for (role, bytes, block) in [("gate", case.gate(), gb), ("up", case.up(), gb), ("down", case.down(), db)] { if let Some(at) = fp16_finite(bytes, block) { - return Err(Refusal::new(name, format!("non-finite FP16 block header in {role} at byte {at}"))); + return Err(r(format!("non-finite FP16 block header in {role} at byte {at}"))); } } if words_le(&case.blob[header.input_at()..]).into_iter().any(|w| !f32::from_bits(w).is_finite()) { - return Err(Refusal::new(name, "non-finite activation")); + return Err(r("non-finite activation".to_owned())); } - Ok(()) + Ok(case) } /// Reads an `.out` file as f32 bit patterns. `expect` is the manifest's (sha256, bytes) for a C++ file; ours has none. @@ -110,27 +49,40 @@ pub(super) fn read_out( tree: &str, expect: Option<(&str, u64)>, ) -> Result, Refusal> { - let (mut f, len) = open_measured(path, name)?; - require_expected_length(name, len, expect)?; - require_length_in_range(name, len, OUT_HEADER)?; - let hdr = read_header::(&mut f, name)?; - validate_out_header(&hdr, len, rows, tree).map_err(|reason| Refusal::new(name, reason))?; - let blob = read_whole(&mut f, name, len, &hdr)?; - require_expected_sha(name, &blob, expect)?; + let r = |reason: String| Refusal::new(name, reason); + let mut f = File::open(path).map_err(|e| r(format!("cannot open: {e}")))?; + let len = f.metadata().map_err(|e| r(format!("cannot stat: {e}")))?.len(); + if let Some((_, bytes)) = expect + && len != bytes + { + return Err(r(format!("length {len} differs from the manifest's {bytes}"))); + } + if len > MAX_FILE_BYTES || len < OUT_HEADER as u64 { + return Err(r(format!("length {len} outside {OUT_HEADER}..={MAX_FILE_BYTES}"))); + } + let mut hdr = [0u8; OUT_HEADER]; + f.read_exact(&mut hdr).map_err(|e| r(format!("cannot read the header: {e}")))?; + validate_out_header(&hdr, len, rows, tree).map_err(r)?; + let mut blob = take_buffer(len as usize).map_err(r)?; + blob[..OUT_HEADER].copy_from_slice(&hdr); + f.read_exact(&mut blob[OUT_HEADER..]).map_err(|e| r(format!("cannot read the body: {e}")))?; + if let Some((sha, _)) = expect + && sha_hex(&blob) != sha + { + return Err(r("sha256 differs from the manifest".to_owned())); + } let bits = words_le(&blob[OUT_HEADER..]); if bits.iter().any(|b| !f32::from_bits(*b).is_finite()) { - return Err(Refusal::new(name, "non-finite value")); + return Err(r("non-finite value".to_owned())); } Ok(bits) } -const MANIFEST_NAME: &str = "manifest.json"; - -/// 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_NAME; + let mname = "manifest.json"; if !mpath.is_file() { let mut r = Refusal::new(mname, "no manifest.json (the writer publishes it last)"); r.incomplete = true; @@ -149,12 +101,28 @@ 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)?; - let names = require_files_agree(&cases, &files)?; - require_listing_known(dir, &names)?; + // the flat files table and the case entries must describe exactly the same files + let mut expected: Vec<(&str, &str, u64)> = cases.iter().flat_map(case_files).collect(); + expected.sort_unstable(); + let mut table: Vec<(&str, &str, u64)> = files.iter().map(|(n, s, b)| (n.as_str(), s.as_str(), *b)).collect(); + table.sort_unstable(); + if expected != table { + return Err(r("the flat files table and the case entries disagree".to_owned())); + } + let names: BTreeSet<&str> = expected.iter().map(|e| e.0).collect(); + let listing = fs::read_dir(dir).map_err(|e| r(format!("cannot list the directory: {e}")))?; + for entry in listing { + let entry = entry.map_err(|e| r(format!("cannot list the directory: {e}")))?; + let n = entry.file_name().to_string_lossy().into_owned(); + if n != mname && !names.contains(n.as_str()) { + return Err(Refusal::new(&n, "file is not in the manifest")); + } + } let file_count = names.len() + 1; for c in &cases { read_case_in(dir, c)?; @@ -164,40 +132,14 @@ pub(super) fn verify_dir(dir: &Path) -> Result { } Ok(Verified { dir: dir.to_owned(), manifest_sha256: sha_hex(&mbytes), provenance, cases, file_count }) } - -/// The flat files table and the case entries must describe exactly the same files; returns their names. -fn require_files_agree<'a>(cases: &'a [CaseEntry], files: &FileTable) -> Result, Refusal> { - let mut expected: Vec<(&str, &str, u64)> = cases.iter().flat_map(case_files).collect(); - expected.sort_unstable(); - let mut table: Vec<(&str, &str, u64)> = files.iter().map(|(n, s, b)| (n.as_str(), s.as_str(), *b)).collect(); - table.sort_unstable(); - if expected != table { - return Err(Refusal::new(MANIFEST_NAME, "the flat files table and the case entries disagree")); - } - Ok(expected.iter().map(|e| e.0).collect()) -} - -/// Every file of the directory is the manifest or listed in it. -fn require_listing_known(dir: &Path, names: &BTreeSet<&str>) -> Result<(), Refusal> { - let listing = - fs::read_dir(dir).map_err(|e| Refusal::new(MANIFEST_NAME, format!("cannot list the directory: {e}")))?; - for entry in listing { - let entry = entry.map_err(|e| Refusal::new(MANIFEST_NAME, format!("cannot list the directory: {e}")))?; - let n = entry.file_name().to_string_lossy().into_owned(); - if n != MANIFEST_NAME && !names.contains(n.as_str()) { - return Err(Refusal::new(&n, "file is not in the manifest")); - } - } - Ok(()) -} impl Outcome { pub(super) fn equal(&self) -> bool { self.mismatches == 0 } } -/// Bitwise on the f32 bit patterns (so -0 and +0 differ) when `tol` is None; otherwise `|ours - ref| <= value * -/// max|ref|` per value (the one metric the reader knows, `TOLERANCE_METRIC`). +/// 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 { @@ -215,7 +157,11 @@ pub(super) fn compare_bits(ours: &[u32], reference: &[u32], tol: Option<&Toleran if err.is_finite() { o.max_abs_error = o.max_abs_error.max(err); } - if is_mismatch(tol, (*a, *b), err, scale) { + 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)); } @@ -226,16 +172,7 @@ pub(super) fn compare_bits(ours: &[u32], reference: &[u32], tol: Option<&Toleran o } -/// Whether one value pair `(ours, reference)` is a mismatch: differing bits when `tol` is None, otherwise an error -/// above `value * scale` (or an error that cannot be ordered). -fn is_mismatch(tol: Option<&Tolerance>, (a, b): (u32, u32), err: f64, scale: f64) -> bool { - match tol { - None => a != b, - Some(t) => err.partial_cmp(&(t.value * scale)).is_none_or(|o| o == std::cmp::Ordering::Greater), - } -} - -// ------------------------------------------------------------------------------------------ record (hand-written JSON) +// ------------------------------------------------------------------------------------------------ record (hand-written JSON) pub(super) fn jstr(s: &str) -> String { let mut o = String::with_capacity(s.len() + 2); @@ -256,103 +193,50 @@ pub(super) fn jstr(s: &str) -> String { } pub(super) fn record_json(r: &RecordInput) -> String { + let p = &r.verified.provenance; let c = r.case; - let tolerance = c.tolerance.as_ref().map_or(String::new(), tolerance_json); + 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)); - let mut j = record_head(r, gu, down); - j += &record_toolchain(r); - j += &record_case(r); - j += &record_placeholders(r, gu, down, &tiny); - j += &format!( - " \"equality\": {{\n \"mode\": \"{}\",\n \"verdict\": \"{}\",\n \"compared_values\": {},\n \ - \"mismatches\": {}{tolerance}\n }}\n}}\n", - if c.tolerance.is_some() { "tolerance" } else { "bitwise" }, - if r.outcome.equal() { "EQUAL" } else { "NOT_EQUAL" }, - r.outcome.compared, - r.outcome.mismatches - ); - j -} - -/// The `tolerance` member of an equality block (with its leading comma) for a case that declares one. -fn tolerance_json(t: &Tolerance) -> String { format!( - ",\n \"tolerance\": {{\"value\": {:e}, \"basis\": {}, \"basis_written_utc\": {}}}", - t.value, - jstr(&format!("{} [metric: {TOLERANCE_METRIC}]", t.basis)), - jstr(&t.basis_written_utc) - ) -} - -/// The record from its opening brace to the `kernel` member. -fn record_head(r: &RecordInput, gu: &str, down: &str) -> String { - format!( - "{{\n \"schema_version\": \"1\",\n \"level\": \"COMPONENT_KERNEL\",\n \"record_id\": {},\n \ - \"created_utc\": {},\n \ - \"run_started_utc\": {},\n \"machine\": {{\"machine_role\": {}, \"cpu_model\": {}, \"gpu_name\": \"none\", \ - \"os\": {}}},\n \"kernel\": {},\n", - jstr(&r.record_id), - jstr(&r.created_utc), - jstr(&r.run_started_utc), - jstr(&r.machine_role), - jstr(&r.cpu_model), - jstr(&r.os), - jstr(&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})", - r.case.rows - )) - ) -} - -/// The `toolchain` member: our compiler and the reference's from the provenance. -fn record_toolchain(r: &RecordInput) -> String { - let p = &r.verified.provenance; - format!( - " \"toolchain\": {{\n \"ours\": {{\"compiler\": {}, \"version\": {}, \"target_triple\": {}, \"flags\": \ - {}}},\n \ - \"reference\": {{\"compiler\": {}, \"version\": {}, \"target_triple\": {}, \"flags\": {}}}\n }},\n", - jstr(&r.ours_compiler), - jstr(&r.ours_version), - jstr(&r.ours_triple), - jstr(&r.ours_flags), - jstr(&p.compiler_id), - jstr(&p.compiler_version), - jstr(&p.target_triple), - jstr(&p.reference_flags) - ) -} - -/// The members that name the case, the hashes, the tree, the regime, the pin and the upstream commit. -fn record_case(r: &RecordInput) -> String { - format!( - " \"case_id\": {},\n \"input_sha256\": {},\n \"kab1_manifest_sha256\": {},\n \"tree\": {{\"ours\": {tree}, \ - \"reference\": {tree}}},\n \"regime\": \"resident\",\n \"pin\": {{\"logical_cpu\": {}, \"sibling_idle\": \ - {}}},\n \ - \"strata_upstream_commit\": {},\n", - jstr(&r.case.id), - jstr(&r.case.in_sha256), - jstr(&r.verified.manifest_sha256), - r.pin_cpu, - r.sibling_idle, - jstr(&r.verified.provenance.engine_strata_pin), - tree = jstr(r.tree) - ) -} - -/// The members that carry no timing: the NOT_MEASURED markers and the A/A noise floor placeholder. -fn record_placeholders(r: &RecordInput, gu: &str, down: &str, tiny: &str) -> String { - format!( - " \"clock_calibration\": {{\"method\": {}, \"ghz_before\": {tiny}, \"ghz_after\": {tiny}, \ - \"max_drift_fraction\": 0, \ - \"slices_total\": 1, \"slices_dropped\": 0}},\n \"rows\": [\n {{\"row_type\": {}, \"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", - jstr(NOT_MEASURED), - jstr(&format!("{gu}+{down} r{} {NOT_MEASURED}", r.case.rows)) + 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/round_records_fn.rs b/crates/native-cpu-expert/examples/kernel_ab/round_records_fn.rs index 4a55a6cf..5839b0a0 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,285 +1,148 @@ -//! 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. +/// 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 round = Round::new(ctx, round_no, done); + 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 trees: Vec<&'static str> = TREES.iter().copied().filter(|t| done.iter().any(|d| d.proc.tree == *t)).collect(); + 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 procs = TreeProcs::find(done, round_no, tree)?; + 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] { - files.push(round.record(&round.slot(&procs, tree, regime, kind))?); + let (ours, reference, ours_tool, ref_tool) = match kind { + Kind::Ab => (rust_a, cpp_a, &ctx.rust_tool, &cpp_tool), + Kind::AaCpp => (cpp_a, cpp_b, &cpp_tool, &cpp_tool), + Kind::AaRust => (rust_a, rust_b, &ctx.rust_tool, &ctx.rust_tool), + }; + let (o, r) = (&ours.regimes[regime], &reference.regimes[regime]); + if (o.copies_k, o.expert_bytes, o.llc_bytes) != (r.copies_k, r.expert_bytes, r.llc_bytes) { + return Err(format!( + "round {round_no} {tree} {regime}: the streamed set differs between {} and {} (K {} vs {}, LLC {} vs {})", + ours.proc.name(), + reference.proc.name(), + o.copies_k, + r.copies_k, + o.llc_bytes, + r.llc_bytes + )); + } + let (equality, equality_note) = match kind { + Kind::Ab => (equality_block(c, &ctx.equality[tree]), "Rust output against the C++ reference .out file of the run directory, from the equality phase of this batch".to_owned()), + _ => { + let (outcome, note) = aa_outcome(ours, reference, c.rows); + (aa_equality_block(&outcome), format!("{note}, the same implementation in two fresh processes")) + } + }; + let kernel = format!( + "routed-expert-gate-up-down {gu}+{down} rows={} regime {regime} ROUND RECORD {} (batch {}, round {round_no}); ours-slot process {}, reference-slot process {}; tree ours: {}; tree reference: {}; equality: {equality_note}; aa_noise_floor is a PLACEHOLDER (n=1, CI 0): the A/A evaluation is S0.10b, this record carries one round's medians only", + c.rows, + match kind { + Kind::Ab => "A/B (ours = Rust, reference = C++)", + Kind::AaCpp => "A/A (C++ process a in the ours slot, C++ process b in the reference slot)", + Kind::AaRust => "A/A (Rust process a in the ours slot, Rust process b in the reference slot)", + }, + ctx.batch, + ours.proc.name(), + reference.proc.name(), + ours.tree_text, + reference.tree_text + ); + let drift = o.max_drift.max(r.max_drift); + // the two processes of this record, earliest first: the clock before the earlier one, after the later one + let (earlier, later) = + if position(ours) <= position(reference) { (ours, reference) } else { (reference, ours) }; + let sibling_idle = ours.sibling_idle == Some(true) && reference.sibling_idle == Some(true); + let streamed = if regime == "STREAMED" { + format!( + ",\n \"streamed\": {{\"copies\": {}, \"expert_bytes\": {}, \"llc_bytes\": {}}}", + o.copies_k, o.expert_bytes, o.llc_bytes + ) + } else { + String::new() + }; + let rowtype = + |unit: &str| format!("{gu}+{down} rows={} {} [{unit}]", c.rows, regime.to_ascii_lowercase()); + let json = format!( + "{{\n \"schema_version\": \"1\",\n \"level\": \"COMPONENT_KERNEL\",\n \"record_id\": {rid},\n \"created_utc\": {created},\n \"run_started_utc\": {started},\n \"machine\": {{\"machine_role\": {role}, \"cpu_model\": {cpu}, \"gpu_name\": \"none\", \"os\": {os}}},\n \"kernel\": {kernel},\n \"toolchain\": {{\n \"ours\": {ot},\n \"reference\": {rt}\n }},\n \"case_id\": {cid},\n \"input_sha256\": {insha},\n \"kab1_manifest_sha256\": {msha},\n \"tree\": {{\"ours\": {tree_q}, \"reference\": {tree_q}}},\n \"regime\": {regime_q}{streamed},\n \"pin\": {{\"logical_cpu\": {pin}, \"sibling_idle\": {sib}}},\n \"strata_upstream_commit\": {commit},\n \"clock_calibration\": {{\"method\": {method}, \"ghz_before\": {g0}, \"ghz_after\": {g1}, \"max_drift_fraction\": {drift}, \"slices_total\": {total}, \"slices_dropped\": {dropped}}},\n \"rows\": [\n {{\"row_type\": {rt_ns}, \"unit\": \"ns\", \"rounds\": 1, \"ours\": {on}, \"reference\": {rn}}},\n {{\"row_type\": {rt_cy}, \"unit\": \"cycles\", \"rounds\": 1, \"ours\": {oc}, \"reference\": {rc}}}\n ],\n \"aa_noise_floor\": {{\"ours_vs_ours\": {{\"n\": 1, \"ci95_low\": 0, \"ci95_high\": 0}}, \"reference_vs_reference\": {{\"n\": 1, \"ci95_low\": 0, \"ci95_high\": 0}}, \"floor_fraction\": 0}},\n \"equality\": {equality}\n}}\n", + rid = jstr(&format!( + "kab1alt-{}-{}-b{}-r{round_no:05}-{}-{tree}-{}", + ctx.verified.provenance.run_id, + c.id, + ctx.batch, + kind.slug(), + regime.to_ascii_lowercase() + )), + created = jstr(&now_utc()), + started = jstr(&ctx.started_utc), + role = jstr(&ctx.machine_role), + cpu = jstr(&ctx.cpu_model), + os = jstr(&ctx.os), + kernel = jstr(&kernel), + ot = tool_json(ours_tool), + rt = tool_json(ref_tool), + cid = jstr(&c.id), + insha = jstr(&c.in_sha256), + msha = jstr(&ctx.verified.manifest_sha256), + tree_q = jstr(tree), + regime_q = jstr(®ime.to_ascii_lowercase()), + pin = ctx.pin, + sib = sibling_idle, + commit = jstr(&p.engine_strata_pin), + method = jstr(&format!( + "{CLOCK_METHOD}; ghz_before is the ghz_at_start of the earlier process of this record ({}), ghz_after the ghz_at_end of the later one ({}); sibling_idle: the SMT sibling stayed under 5 percent busy during both processes; max_drift_fraction is the largest |g1 - g0| / g0 over every slice of the two processes of this record, slices_total and slices_dropped count their requested and dropped slices", + earlier.proc.name(), + later.proc.name() + )), + g0 = jnum(earlier.ghz_start, 6), + g1 = jnum(later.ghz_end, 6), + drift = jnum(drift, 6), + total = o.requested + r.requested, + dropped = o.dropped + r.dropped, + rt_ns = jstr(&rowtype("ns")), + rt_cy = jstr(&rowtype("cycles")), + on = stat_json(&side_stat(o, false)), + rn = stat_json(&side_stat(r, false)), + oc = stat_json(&side_stat(o, true)), + rc = stat_json(&side_stat(r, true)), + ); + files.push(( + format!("r{round_no:05}.{}.{tree}.{}.json", kind.slug(), regime.to_ascii_lowercase()), + json, + )); } } } Ok(files) } -fn find_proc<'a>(done: &'a [ProcOut], round_no: u32, imp: Impl, tree: &str, rep: char) -> Result<&'a ProcOut, String> { - 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())) -} - -/// The four processes of one tree in a round: C++ and Rust, replicates `a` and `b`. -struct TreeProcs<'a> { - cpp_a: &'a ProcOut, - cpp_b: &'a ProcOut, - rust_a: &'a ProcOut, - rust_b: &'a ProcOut, -} - -impl<'a> TreeProcs<'a> { - fn find(done: &'a [ProcOut], round_no: u32, tree: &str) -> Result { - Ok(Self { - cpp_a: find_proc(done, round_no, Impl::Cpp, tree, 'a')?, - cpp_b: find_proc(done, round_no, Impl::Cpp, tree, 'b')?, - rust_a: find_proc(done, round_no, Impl::Rust, tree, 'a')?, - rust_b: find_proc(done, round_no, Impl::Rust, tree, 'b')?, - }) - } -} - -/// What one round shares between its records. -struct Round<'a> { - ctx: &'a BatchCtx<'a>, - round_no: u32, - done: &'a [ProcOut], - cpp_tool: Tool, - gu: &'static str, - down: &'static str, -} - -/// One record of a round: the pair of processes that fill its ours and reference slots, and the tools that built them. -struct Slot<'a> { - tree: &'static str, - regime: &'static str, - kind: Kind, - ours: &'a ProcOut, - reference: &'a ProcOut, - ours_tool: &'a Tool, - ref_tool: &'a Tool, -} - -impl Slot<'_> { - fn regime_lower(&self) -> String { - self.regime.to_ascii_lowercase() - } - /// The regime stats of the ours and the reference process. - fn stats(&self) -> (&RegimeStat, &RegimeStat) { - (&self.ours.regimes[self.regime], &self.reference.regimes[self.regime]) - } -} - -impl<'a> Round<'a> { - fn new(ctx: &'a BatchCtx<'a>, round_no: u32, done: &'a [ProcOut]) -> Self { - 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)); - Self { ctx, round_no, done, cpp_tool, gu, down } - } - - fn slot<'s>(&'s self, procs: &TreeProcs<'s>, tree: &'static str, regime: &'static str, kind: Kind) -> Slot<'s> { - let (ours, reference, ours_tool, ref_tool) = match kind { - Kind::Ab => (procs.rust_a, procs.cpp_a, &self.ctx.rust_tool, &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, &self.ctx.rust_tool, &self.ctx.rust_tool), - }; - Slot { tree, regime, kind, ours, reference, ours_tool, ref_tool } - } - - /// The file name and the text of one record. - fn record(&self, s: &Slot) -> Result<(String, String), String> { - self.require_same_streamed_set(s)?; - let (equality, equality_note) = self.equality_of(s); - let kernel = self.kernel_text(s, &equality_note); - let mut json = self.record_head(s, &kernel); - json += &self.record_ids(s); - json += &self.record_clock(s); - json += &self.record_rows(s, &equality); - let name = format!("r{:05}.{}.{}.{}.json", self.round_no, s.kind.slug(), s.tree, s.regime_lower()); - Ok((name, json)) - } - - /// Both processes of a record timed the same streamed set. - fn require_same_streamed_set(&self, s: &Slot) -> Result<(), String> { - let (o, r) = s.stats(); - if (o.copies_k, o.expert_bytes, o.llc_bytes) != (r.copies_k, r.expert_bytes, r.llc_bytes) { - return Err(format!( - "round {} {} {}: the streamed set differs between {} and {} (K {} vs {}, LLC {} vs {})", - self.round_no, - s.tree, - s.regime, - s.ours.proc.name(), - s.reference.proc.name(), - o.copies_k, - r.copies_k, - o.llc_bytes, - r.llc_bytes - )); - } - Ok(()) - } - - /// The `equality` block of the record and the note that says where it comes from. - fn equality_of(&self, s: &Slot) -> (String, String) { - if s.kind == Kind::Ab { - let note = "Rust output against the C++ reference .out file of the run directory, from the equality phase \ - of this batch"; - return (equality_block(self.ctx.case, &self.ctx.equality[s.tree]), note.to_owned()); - } - let (outcome, note) = aa_outcome(s.ours, s.reference, self.ctx.case.rows); - (aa_equality_block(&outcome), format!("{note}, the same implementation in two fresh processes")) - } - - fn kernel_text(&self, s: &Slot, equality_note: &str) -> String { - let (gu, down, regime, round_no) = (self.gu, self.down, s.regime, self.round_no); - let label = match s.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)", - }; - format!( - "routed-expert-gate-up-down {gu}+{down} rows={} regime {regime} ROUND RECORD {label} (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", - self.ctx.case.rows, - self.ctx.batch, - s.ours.proc.name(), - s.reference.proc.name(), - s.ours.tree_text, - s.reference.tree_text - ) - } - - /// The record from its opening brace through the `toolchain` member. - fn record_head(&self, s: &Slot, kernel: &str) -> String { - let ctx = self.ctx; - format!( - "{{\n \"schema_version\": \"1\",\n \"level\": \"COMPONENT_KERNEL\",\n \"record_id\": {},\n \ - \"created_utc\": {},\n \"run_started_utc\": {},\n \"machine\": {{\"machine_role\": {}, \"cpu_model\": \ - {}, \ - \"gpu_name\": \"none\", \"os\": {}}},\n \"kernel\": {},\n \"toolchain\": {{\n \"ours\": {},\n \ - \"reference\": {}\n }},\n", - jstr(&format!( - "kab1alt-{}-{}-b{}-r{:05}-{}-{}-{}", - ctx.verified.provenance.run_id, - ctx.case.id, - ctx.batch, - self.round_no, - s.kind.slug(), - s.tree, - s.regime_lower() - )), - jstr(&now_utc()), - jstr(&ctx.started_utc), - jstr(&ctx.machine_role), - jstr(&ctx.cpu_model), - jstr(&ctx.os), - jstr(kernel), - tool_json(s.ours_tool), - tool_json(s.ref_tool) - ) - } - - /// The members that name the case, the hashes, the tree, the regime, the pin and the upstream commit. - fn record_ids(&self, s: &Slot) -> String { - let ctx = self.ctx; - let (o, _) = s.stats(); - let streamed = if s.regime == "STREAMED" { - format!( - ",\n \"streamed\": {{\"copies\": {}, \"expert_bytes\": {}, \"llc_bytes\": {}}}", - o.copies_k, o.expert_bytes, o.llc_bytes - ) - } else { - String::new() - }; - let sibling_idle = s.ours.sibling_idle == Some(true) && s.reference.sibling_idle == Some(true); - format!( - " \"case_id\": {},\n \"input_sha256\": {},\n \"kab1_manifest_sha256\": {},\n \"tree\": {{\"ours\": \ - {tree_q}, \ - \"reference\": {tree_q}}},\n \"regime\": {}{streamed},\n \"pin\": {{\"logical_cpu\": {}, \ - \"sibling_idle\": {sibling_idle}}},\n \"strata_upstream_commit\": {},\n", - jstr(&ctx.case.id), - jstr(&ctx.case.in_sha256), - jstr(&ctx.verified.manifest_sha256), - jstr(&s.regime_lower()), - ctx.pin, - jstr(&ctx.verified.provenance.engine_strata_pin), - tree_q = jstr(s.tree) - ) - } - - /// The `clock_calibration` member: the clock before the earlier process of the record and after the later one. - fn record_clock(&self, s: &Slot) -> String { - let (o, r) = s.stats(); - let drift = o.max_drift.max(r.max_drift); - let position = |p: &ProcOut| self.done.iter().position(|d| d.proc == p.proc).unwrap_or(0); - let (earlier, later) = - if position(s.ours) <= position(s.reference) { (s.ours, s.reference) } else { (s.reference, s.ours) }; - let method = 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() - ); - format!( - " \"clock_calibration\": {{\"method\": {}, \"ghz_before\": {}, \"ghz_after\": {}, \"max_drift_fraction\": \ - {}, \ - \"slices_total\": {}, \"slices_dropped\": {}}},\n", - jstr(&method), - jnum(earlier.ghz_start, 6), - jnum(later.ghz_end, 6), - jnum(drift, 6), - o.requested + r.requested, - o.dropped + r.dropped - ) - } - - /// The `rows` member (ns and cycles), the A/A noise floor placeholder and the `equality` block. - fn record_rows(&self, s: &Slot, equality: &str) -> String { - let (o, r) = s.stats(); - let rowtype = - |unit: &str| format!("{}+{} rows={} {} [{unit}]", self.gu, self.down, self.ctx.case.rows, s.regime_lower()); - format!( - " \"rows\": [\n {{\"row_type\": {}, \"unit\": \"ns\", \"rounds\": 1, \"ours\": {}, \"reference\": \ - {}}},\n \ - {{\"row_type\": {}, \"unit\": \"cycles\", \"rounds\": 1, \"ours\": {}, \"reference\": {}}}\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", - jstr(&rowtype("ns")), - stat_json(&side_stat(o, false)), - stat_json(&side_stat(r, false)), - jstr(&rowtype("cycles")), - stat_json(&side_stat(o, true)), - stat_json(&side_stat(r, true)) - ) - } -} - 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 @@ -288,43 +151,29 @@ pub(super) fn aa_equality_block(o: &Outcome) -> String { pub(super) fn parse_alt_args(args: &[String]) -> Result { let f = Flags::parse(args, &ALT_FLAGS)?; - let core = read_alt_core(&f)?; - build_alt_args(&f, core) -} - -/// The counts and the case of the alternation command line, checked in the order of the command line's own rules. -struct AltCore { - rounds: u32, - batch: u32, - case: String, - slices: usize, -} - -fn read_alt_core(f: &Flags) -> Result { - let rounds = f.need_number::("rounds")?; - let batch = f.need_number::("batch")?; + 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()); } - let case = f.case_id()?; + let case = f.req("case")?.to_owned(); + if !valid_id(&case) { + return Err(format!("--case {case:?} is not a plain identifier")); + } let slices = f.number::("slices")?.unwrap_or(20); if !(1..=100_000).contains(&slices) { return Err("--slices must be 1..100000".to_owned()); } - Ok(AltCore { rounds, batch, case, slices }) -} - -fn build_alt_args(f: &Flags, core: AltCore) -> Result { Ok(AltArgs { dir: PathBuf::from(f.req("run-dir")?), - case: core.case, - rounds: core.rounds, - batch: core.batch, - pin: f.need_number::("pin")?, + case, + rounds, + 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: core.slices, + 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/run_regime_fn.rs b/crates/native-cpu-expert/examples/kernel_ab/run_regime_fn.rs index e7e3e761..58f7254a 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 @@ -4,27 +4,8 @@ use super::*; pub(super) fn run_regime(t: &mut Timed, spec: &RegimeSpec) -> Result { - let next = warm_up(t, spec)?; - let sampled = sample_slices(t, spec, next)?; - let json = regime_json(spec, &sampled); - Ok(RegimeRun { - json, - kept: sampled.kept.len(), - ok: !sampled.kept.is_empty() && sampled.migrated.is_none_or(|m| m == 0), - }) -} - -/// The slices of one regime: kept and dropped with their index, and (Linux) how many left the pinned CPU. -struct Sampled { - kept: Numbered, - dropped: Numbered, - migrated: Option, -} - -/// Warm-up (not recorded): tables and buffers, and for STREAMED one full pass over the copies so every page is -/// resident. Returns the index of the next copy to call. -fn warm_up(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 for _ in 0..3 { t.call(spec.copies[next % spec.copies.len()])?; next += 1; @@ -35,58 +16,24 @@ fn warm_up(t: &mut Timed, spec: &RegimeSpec) -> Result { next += 1; } } - Ok(next) -} - -fn sample_slices(t: &mut Timed, spec: &RegimeSpec, mut next: usize) -> Result { 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 { let before = current_cpu(); let s = time_slice(t, &spec.copies, spec.slice_ms, &mut next)?; if let Some(m) = migrated.as_mut() - && left_pin(before, spec.pin) + && (before != Some(spec.pin) || current_cpu() != Some(spec.pin)) { *m += 1; } if s.moved { dropped.push((i, s)) } else { kept.push((i, s)) } } - Ok(Sampled { kept, dropped, migrated }) -} - -/// The slice started off the pinned CPU or ended off it. -fn left_pin(before: Option, pin: usize) -> bool { - before != Some(pin) || current_cpu() != Some(pin) -} - -fn regime_json(spec: &RegimeSpec, s: &Sampled) -> String { - let ns: Vec = s.kept.iter().map(|k| k.1.ns_per_call).collect(); - let cyc: Vec = s.kept.iter().map(|k| k.1.cycles_per_call).collect(); - let mut json = regime_json_set(spec); - json += &format!( - "\"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 {}]}}", - jnum(spec.slice_ms, 1), - spec.slices, - s.kept.len(), - s.dropped.len(), - spec.selfcheck, - s.migrated.map_or("null".to_owned(), |m| m.to_string()), - median_json(&ns, 3), - median_json(&cyc, 1), - slice_list_json(&s.kept), - slice_list_json(&s.dropped) - ); - json -} - -/// The members of the regime JSON that describe the set of copies and the last-level cache. -fn regime_json_set(spec: &RegimeSpec) -> String { - format!( - "{{\"regime\": {}, \"copies_k\": {}, \"expert_bytes\": {}, \"copy_stride_bytes\": {}, \"working_set_bytes\": \ - {}, \ - \"llc_level\": {}, \"llc_bytes\": {}, \"llc_source\": {}, \"working_set_over_llc\": {}, ", + 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 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, @@ -95,16 +42,19 @@ fn regime_json_set(spec: &RegimeSpec) -> String { spec.llc.level, spec.llc.bytes, jstr(&spec.llc.source), - spec.copies.len() > 1 - ) -} - -fn median_json(v: &[f64], decimals: usize) -> String { - if v.is_empty() { "null".to_owned() } else { jnum(median_of(v), decimals) } -} - -fn slice_list_json(v: &[(usize, Slice)]) -> String { - v.iter().map(|(i, s)| slice_json(s, *i)).collect::>().join(",\n ") + spec.copies.len() > 1, + jnum(spec.slice_ms, 1), + spec.slices, + kept.len(), + dropped.len(), + spec.selfcheck, + migrated.map_or("null".to_owned(), |m| m.to_string()), + med(&ns, 3), + med(&cyc, 1), + list(&kept), + list(&dropped) + ); + Ok(RegimeRun { json, kept: kept.len(), ok: !kept.is_empty() && migrated.is_none_or(|m| m == 0) }) } pub(super) fn f32_bits_sha(values: &[f32]) -> String { 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 6eb606fb..d01283d1 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,7 +122,7 @@ pub(super) struct Expect<'a> { pub(super) pin: usize, } -// -------------------------------------------------------------------------------------------- alternate: round records +// ------------------------------------------------------------------------------------------------ alternate: round records pub(super) struct Tool { pub(super) compiler: String, @@ -159,7 +159,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/time_report.rs b/crates/native-cpu-expert/examples/kernel_ab/time_report.rs deleted file mode 100644 index 4464d4ad..00000000 --- a/crates/native-cpu-expert/examples/kernel_ab/time_report.rs +++ /dev/null @@ -1,189 +0,0 @@ -//! The KAB1-time JSON that `kernel_ab time` writes (writer "rust"), one section after the other. - -#[allow(unused_imports)] -use super::*; - -/// Everything the JSON says: what was prepared, what was measured, the pin at the end and the hash of the output. -pub(super) struct TimeReport<'a> { - pub(super) p: &'a Prepared, - pub(super) end: &'a PinEnd, - pub(super) m: &'a Measured, - pub(super) output_sha: &'a str, -} - -/// The whole JSON text. The sections read the host (load average, current CPU, the clock) as they are built, in this -/// order. -pub(super) fn render_time_json(r: &TimeReport) -> String { - let mut j = String::from( - "{\n \"format\": \"KAB1-time\",\n \"version\": 1,\n \"mode\": \"time\",\n \"writer\": \"rust\",\n", - ); - j += §ion_command(r); - j += §ion_case(r); - j += §ion_tree(r); - j += §ion_pool(r); - j += §ion_pin(r); - j += §ion_buffers(r); - j += §ion_clock(r); - j += §ion_build(); - j += §ion_result(r); - j -} - -/// The command line of the run, as `kab time` would print it. -fn time_command_line(r: &TimeReport) -> String { - let t = &r.p.t; - format!( - "time --run-dir {} --case {} --slices {} --pin {} --out {}{}{}", - t.dir.display(), - t.case, - t.slices, - t.pin, - t.out.display(), - if r.p.has_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 section_command(r: &TimeReport) -> String { - format!( - " \"command_line\": {},\n \"run_dir\": {},\n \"manifest_sha256\": {},\n", - jstr(&time_command_line(r)), - jstr(&r.p.t.dir.display().to_string()), - jstr(&r.p.tc.manifest_sha) - ) -} - -fn section_case(r: &TimeReport) -> String { - let header = r.p.tc.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)); - 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(&r.p.t.case), - header.gu, - header.down, - jstr(gu_name), - jstr(down_name), - header.rows, - jstr(&format!("case-{}.in", r.p.t.case)), - jstr(&r.p.tc.in_sha256), - r.p.plan.expert_bytes - ) -} - -fn section_tree(r: &TimeReport) -> String { - format!( - " \"tree\": {},\n \"tree_detail\": {{\"tree\": {}, \"cpu_report\": [{}], \"strata_env\": {}}},\n \ - \"effective_env\": {},\n", - jstr(r.p.tree), - jstr(r.p.tree), - r.p.report.iter().map(|l| jstr(l)).collect::>().join(", "), - json_env(&r.p.env), - json_env(&r.p.env) - ) -} - -fn section_pool(r: &TimeReport) -> 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", - r.end - .threads - .iter() - .map(|(n, c)| format!( - "{{\"name\": {}, \"cpu\": {}}}", - jstr(n), - c.map_or("null".to_owned(), |c| c.to_string()) - )) - .collect::>() - .join(", ") - ) -} - -/// A busy fraction with four decimals, or `null` when it is unknown. -fn busy_json(f: Option) -> String { - f.map_or("null".to_owned(), |v| jnum(v, 4)) -} - -fn section_pin(r: &TimeReport) -> String { - let (s, e) = (&r.p.start, r.end); - let sibling_busy = if s.sibling.is_some() { busy_json(busy_fraction(s.sib0, e.sib1)) } else { "null".to_owned() }; - 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", - r.p.t.pin, - jstr(&s.sib_text), - s.sibling.map_or("null".to_owned(), |s| s.to_string()), - jstr(&read_text(&format!("{}/topology/core_id", s.cpu_dir))), - busy_json(busy_fraction(s.pin0, e.pin1)), - sibling_busy, - jstr(&read_text(&format!("{}/cpufreq/scaling_governor", s.cpu_dir))), - jstr(&read_text("/sys/devices/system/cpu/cpufreq/boost")), - jstr(&s.load0), - jstr(&read_text("/proc/loadavg")), - current_cpu().map_or("null".to_owned(), |c| c.to_string()) - ) -} - -fn section_buffers(r: &TimeReport) -> String { - let stride = r.p.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 section_clock(r: &TimeReport) -> 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(r.m.ghz0, 6), - jnum(r.m.ghz1, 6) - ) -} - -fn section_build() -> 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()) - ) -} - -/// The selfcheck, the final check, the output hash, the duration and the regimes. -fn section_result(r: &TimeReport) -> String { - let (selfcheck, final_same) = (r.m.selfcheck, r.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(r.output_sha), - mono_ns() - r.p.wall0, - r.m.regimes.jsons.join(",\n ") - ) -} diff --git a/crates/native-cpu-expert/examples/kernel_ab/time_session.rs b/crates/native-cpu-expert/examples/kernel_ab/time_session.rs deleted file mode 100644 index aaaea488..00000000 --- a/crates/native-cpu-expert/examples/kernel_ab/time_session.rs +++ /dev/null @@ -1,283 +0,0 @@ -//! The stages of `kernel_ab time` before the JSON is written: the pin and what is known about it, the case, the -//! streamed set, the buffers and the measurement of the two regimes. - -#[allow(unused_imports)] -use super::*; - -/// What is known about the pinned CPU before the run: its SMT sibling, the jiffies of both and the load average. -pub(super) struct PinStart { - pub(super) cpu_dir: String, - pub(super) sib_text: String, - pub(super) sibling: Option, - pub(super) sib0: Option<(u64, u64)>, - pub(super) pin0: Option<(u64, u64)>, - pub(super) load0: String, -} - -/// Pins the process first (before any buffer or pool exists, so the pool's threads inherit the mask); then the facts -/// about the pin. -pub(super) 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)); - } - if cfg!(target_os = "linux") && current_cpu() != Some(t.pin) { - return Err(format!("the process is not running on CPU {} after the pin", t.pin)); - } - let cpu_dir = format!("/sys/devices/system/cpu/cpu{}", t.pin); - let sib_text = read_text(&format!("{cpu_dir}/topology/thread_siblings_list")); - let sibling = parse_cpu_list(&sib_text).into_iter().rfind(|c| *c != t.pin); - let sib0 = sibling.and_then(proc_stat_cpu); - let pin0 = proc_stat_cpu(t.pin); - let load0 = read_text("/proc/loadavg"); - Ok(PinStart { cpu_dir, sib_text, sibling, sib0, pin0, load0 }) -} - -/// What `cmd_time` knows before the first kernel call: the command line, the pin, the case, the host report and the -/// streamed set. -pub(super) struct Prepared { - pub(super) t: TimeArgs, - pub(super) has_slice_ms: bool, - pub(super) wall0: u64, - pub(super) start: PinStart, - pub(super) tc: TimeCase, - pub(super) env: BTreeMap, - pub(super) report: Vec, - pub(super) tree: &'static str, - pub(super) plan: StreamPlan, -} - -pub(super) fn prepare_time_run(args: &[String]) -> Result { - let t = parse_time_args(args)?; - let wall0 = mono_ns(); - let start = pin_and_probe(&t)?; - let tc = load_time_case(&t)?; - 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")?; - let plan = plan_streamed_set(&t, &tc.case)?; - Ok(Prepared { has_slice_ms: args.iter().any(|a| a == "--slice-ms"), t, wall0, start, tc, env, report, tree, plan }) -} - -/// The pool is created AFTER the pin (its worker inherits the one-CPU mask: rust_platform::cores sees a one-CPU -/// affinity) and computes the case once, unaligned: the output every later call must reproduce bit for bit. -pub(super) fn first_call(case: &CaseIn) -> Result<(DirectCpuPool, Vec), String> { - let mut pool = DirectCpuPool::new(1).map_err(|e| format!("DirectCpuPool::new(1) failed: {e:?}"))?; - let want = compute_case(&mut pool, case)?; - Ok((pool, want)) -} - -/// What is known about the pinned CPU after the run. -pub(super) struct PinEnd { - pub(super) threads: Vec<(String, Option)>, - pub(super) sib1: Option<(u64, u64)>, - pub(super) pin1: Option<(u64, u64)>, -} - -pub(super) fn read_pin_end(start: &PinStart, pin: usize) -> PinEnd { - let threads = observed_threads(); - let sib1 = start.sibling.and_then(proc_stat_cpu); - let pin1 = proc_stat_cpu(pin); - PinEnd { threads, sib1, pin1 } -} - -/// The case under test: the KAB1 reader rule (validate, then use) and the manifest and case input hashes. -pub(super) struct TimeCase { - pub(super) manifest_sha: String, - pub(super) in_sha256: String, - pub(super) case: CaseIn, -} - -pub(super) fn load_time_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())?; - Ok(TimeCase { manifest_sha, in_sha256: entry.in_sha256.clone(), case }) -} - -/// The streamed set: K copies of the expert, K x stride at least 2 x the last-level cache of the pinned CPU (the design -/// choice of kab_time.cpp). -pub(super) struct StreamPlan { - pub(super) llc: Llc, - pub(super) stride: usize, - pub(super) copies_k: usize, - pub(super) expert_bytes: usize, -} - -pub(super) fn plan_streamed_set(t: &TimeArgs, case: &CaseIn) -> Result { - let expert_bytes = case.weights().len(); - let llc = resolve_llc(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, expert_bytes }) -} - -/// The last-level cache: the `--llc-bytes` override, else sysfs. -fn resolve_llc(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() } - } - (None, Some(l)) => l, - (None, None) => { - return Err(format!("cannot read the last-level cache size of CPU {} from sysfs; pass --llc-bytes", t.pin)); - } - }; - if llc.bytes == 0 { - return Err("--llc-bytes must be positive".to_owned()); - } - Ok(llc) -} - -/// The aligned buffers the timed calls read: the activations, one resident copy of the expert and the streamed copies. -pub(super) struct TimeBuffers { - tokens: Arena, - resident: Arena, - streamed: Arena, -} - -pub(super) fn fill_buffers(case: &CaseIn, plan: &StreamPlan) -> TimeBuffers { - let rows = case.header.rows; - let weights = case.weights(); - let mut tokens = Arena::::new(rows * H); - tokens.slice_mut(rows * H).copy_from_slice(&case.input()); - let mut resident = Arena::::new(plan.stride); - resident.slice_mut(plan.expert_bytes).copy_from_slice(weights); - let mut streamed = Arena::::new(plan.stride * plan.copies_k); - for k in 0..plan.copies_k { - let all = streamed.slice_mut(plan.stride * plan.copies_k); - all[k * plan.stride..k * plan.stride + plan.expert_bytes].copy_from_slice(weights); - } - TimeBuffers { tokens, resident, streamed } -} - -impl TimeBuffers { - /// The call under time: one group of one expert through the crate's public pool. - pub(super) fn timed<'a>(&'a self, pool: DirectCpuPool, header: InHeader) -> 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: self.tokens.slice(header.rows * H), - out: vec![0.0f32; header.rows * H], - }) - } - - pub(super) fn copies(&self, plan: &StreamPlan) -> Copies<'_> { - let all = self.streamed.slice(plan.stride * plan.copies_k); - Copies { - resident: vec![self.resident.slice(plan.expert_bytes)], - streamed: (0..plan.copies_k).map(|k| &all[k * plan.stride..k * plan.stride + plan.expert_bytes]).collect(), - } - } -} - -/// The copies of the expert one regime cycles over. -pub(super) struct Copies<'a> { - resident: Vec<&'a [u8]>, - streamed: Vec<&'a [u8]>, -} - -/// What the measurement found: the selfcheck, the clock at both ends, the regime JSON texts and the final output check. -pub(super) struct Measured { - pub(super) selfcheck: bool, - pub(super) ghz0: f64, - pub(super) ghz1: f64, - pub(super) regimes: RegimeResults, - pub(super) final_same: bool, -} - -/// The JSON texts of the regimes that ran, whether all were fine and how many slices each kept. -pub(super) struct RegimeResults { - pub(super) jsons: Vec, - pub(super) all_ok: bool, - pub(super) kept_res: usize, - pub(super) kept_stm: usize, -} - -/// Selfcheck, clock, the two regimes, clock, and the final call against the first call's output. -pub(super) fn measure( - t: &TimeArgs, - plan: &StreamPlan, - timed: &mut Timed, - copies: &Copies, - want_bits: &[u32], -) -> Result { - let last = plan.copies_k - 1; - let selfcheck = run_selfcheck(timed, [copies.resident[0], copies.streamed[0], copies.streamed[last]], want_bits)?; - let ghz0 = core_ghz(); - let regimes = run_regimes(t, plan, timed, copies, selfcheck)?; - let ghz1 = core_ghz(); - timed.call(copies.resident[0])?; - let final_same = same_bits(&timed.out, want_bits); - Ok(Measured { selfcheck, ghz0, ghz1, regimes, final_same }) -} - -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; true, or an error. -fn run_selfcheck(timed: &mut Timed, weights: [&[u8]; 3], want_bits: &[u32]) -> Result { - let mut selfcheck = true; - for w in weights { - timed.call(w)?; - 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) -} - -fn regime_spec<'a>( - t: &TimeArgs, - plan: &'a StreamPlan, - label: &'a str, - copies: Vec<&'a [u8]>, - selfcheck: bool, -) -> RegimeSpec<'a> { - RegimeSpec { - label, - copies, - expert_bytes: plan.expert_bytes, - stride: plan.stride, - llc: &plan.llc, - slices: t.slices, - slice_ms: t.slice_ms, - pin: t.pin, - selfcheck, - } -} - -fn run_regimes( - t: &TimeArgs, - plan: &StreamPlan, - timed: &mut Timed, - copies: &Copies, - selfcheck: bool, -) -> Result { - let mut results = RegimeResults { jsons: Vec::new(), all_ok: true, kept_res: 0, kept_stm: 0 }; - for (label, set, sel) in - [("RESIDENT", &copies.resident, RegimeSel::Resident), ("STREAMED", &copies.streamed, RegimeSel::Streamed)] - { - if t.regime != RegimeSel::Both && t.regime != sel { - continue; - } - let r = run_regime(timed, ®ime_spec(t, plan, label, set.clone(), selfcheck))?; - results.all_ok &= r.ok; - if sel == RegimeSel::Resident { - results.kept_res = r.kept - } else { - results.kept_stm = r.kept - } - results.jsons.push(r.json); - } - Ok(results) -} 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 d4522e3c..3f67a3d9 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,12 +1,16 @@ -//! 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 { - require_magic_and_version(h)?; + if le32(h, 0) != IN_MAGIC { + return Err(format!("wrong magic 0x{:08x}, expected 0x{IN_MAGIC:08x}", le32(h, 0))); + } + if le32(h, 4) != 1 { + return Err(format!("unsupported version {}, expected 1", le32(h, 4))); + } let (gu, down) = (le32(h, 8) as i32, le32(h, 12) as i32); let Some(&(_, _, gq, gb, _)) = gate_up_row(gu) else { return Err(format!("gate/up type {gu} is not in the KAB1 list")); @@ -15,8 +19,14 @@ pub(super) fn validate_in_header(h: &[u8; IN_HEADER], file_len: u64) -> Result Result Result<(), String> { - if le32(h, 0) != IN_MAGIC { - return Err(format!("wrong magic 0x{:08x}, expected 0x{IN_MAGIC:08x}", le32(h, 0))); - } - if le32(h, 4) != 1 { - return Err(format!("unsupported version {}, expected 1", le32(h, 4))); - } - Ok(()) -} - -/// The row count is in range and the embedding and feed-forward widths are the ones this reader knows. -fn require_rows_and_dims(h: &[u8; IN_HEADER], rows: usize) -> Result<(), String> { - if !(1..=MAX_ROWS).contains(&rows) { - return Err(format!("rows {rows} outside 1..={MAX_ROWS}")); - } - if le32(h, 20) as usize != H || le32(h, 24) as usize != FF { - return Err(format!("n_embd {} / n_ff {} differ from {H} / {FF}", le32(h, 20), le32(h, 24))); - } - Ok(()) -} - /// Pure: 20 bytes and the file length. pub(super) fn validate_out_header(h: &[u8; OUT_HEADER], file_len: u64, rows: usize, tree: &str) -> Result<(), String> { if le32(h, 0) != OUT_MAGIC { @@ -84,167 +73,109 @@ 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_file_table(m)?; - require_unique_cases(&cases)?; - Ok((provenance, cases, files)) -} - -/// The provenance block and the time the reference run was built (a tolerance basis may not be written after it). -fn parse_provenance(m: &Json) -> Result<(Provenance, &str), String> { let p = m.req("provenance")?; let flags = p.req("flags")?; - let commit = read_commit(p)?; - let built = read_built(p)?; + let commit = p.str("engine_strata_pin")?; + if !is_hex(commit, 7, 40) { + return Err("provenance.engine_strata_pin is not a commit hash".to_owned()); + } + let built = p.str("built_at_utc")?; + if !is_utc(built) { + return Err("provenance.built_at_utc is not a UTC timestamp".to_owned()); + } + let avx512_ok = match p.get("avx512_ok") { + Some(Json::Bool(b)) => Some(*b), + _ => None, + }; let provenance = Provenance { run_id: m.str("run_id")?.to_owned(), engine_strata_pin: commit.to_owned(), compiler_id: p.str("compiler_id")?.to_owned(), compiler_version: p.str("compiler_version")?.to_owned(), target_triple: p.str("target_triple")?.to_owned(), - reference_flags: reference_flags(flags)?, - avx512_ok: read_avx512_ok(p), + reference_flags: format!( + "strata_cxx_flags: {}; ggml_cpu_arch_flags: {}", + flags.str("strata_cxx_flags")?, + flags.str("ggml_cpu_arch_flags")? + ), + avx512_ok, }; - Ok((provenance, built)) -} - -/// Whether the reference build had AVX-512; None when the manifest does not say. -fn read_avx512_ok(p: &Json) -> Option { - match p.get("avx512_ok") { - Some(Json::Bool(b)) => Some(*b), - _ => None, - } -} - -fn read_commit(p: &Json) -> Result<&str, String> { - let commit = p.str("engine_strata_pin")?; - if !is_hex(commit, 7, 40) { - return Err("provenance.engine_strata_pin is not a commit hash".to_owned()); - } - Ok(commit) -} - -fn read_built(p: &Json) -> Result<&str, String> { - let built = p.str("built_at_utc")?; - if !is_utc(built) { - return Err("provenance.built_at_utc is not a UTC timestamp".to_owned()); - } - Ok(built) -} - -/// The compile flags of the reference build, as one line. -fn reference_flags(flags: &Json) -> Result { - Ok(format!( - "strata_cxx_flags: {}; ggml_cpu_arch_flags: {}", - flags.str("strata_cxx_flags")?, - flags.str("ggml_cpu_arch_flags")? - )) -} - -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 { - cases.push(parse_case(c, built)?); - } - Ok(cases) -} - -/// The id, the row count and the input file name of a case. -struct CaseHead { - id: String, - rows: usize, - in_name: String, -} - -fn read_case_head(c: &Json) -> Result { - 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(CaseHead { id, rows, in_name }) -} - -fn parse_case(c: &Json, built: &str) -> Result { - let CaseHead { id, rows, in_name } = read_case_head(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 }) -} - -/// The C++ output file of every tree of the case. -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 id = c.str("id")?.to_owned(); + if !valid_id(&id) { + return Err(format!("case id {id:?} is not a plain identifier")); } - outs.push(OutRef { - tree, - name, - sha256: c.str(&format!("{key}_sha256"))?.to_owned(), - bytes: c.uint(&format!("{key}_bytes"))?, + 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, }); } - Ok(outs) -} - -/// None for a bitwise case; the declared tolerance for a tolerance case; the two must agree with `equality`. -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(_)) => read_tolerance(t, id, built).map(Some), - (other, _) => Err(format!( - "case {id}: equality {other:?} and tolerance disagree (bitwise needs null, tolerance an object)" - )), - } -} - -fn read_tolerance(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 = read_tolerance_value(t, id)?; - let basis = t.str("basis")?.to_owned(); - let written = t.str("basis_written_utc")?.to_owned(); - require_basis(id, &basis, &written, built)?; - Ok(Tolerance { value, basis, basis_written_utc: written }) -} - -fn read_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")) -} - -/// The basis is stated, dated in UTC, and written no later than the reference run. -fn require_basis(id: &str, basis: &str, written: &str, built: &str) -> Result<(), String> { - 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 > built { - return Err(format!("case {id}: the tolerance basis was written {written}, after the reference run {built}")); - } - Ok(()) -} - -fn parse_file_table(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 { @@ -254,13 +185,8 @@ fn parse_file_table(m: &Json) -> Result { } 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 require_unique_cases(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)); } @@ -270,7 +196,7 @@ fn require_unique_cases(cases: &[CaseEntry]) -> Result<(), String> { } } } - Ok(()) + Ok((provenance, cases, files)) } pub(super) fn case_files(c: &CaseEntry) -> Vec<(&str, &str, u64)> { @@ -290,10 +216,6 @@ impl CaseIn { let s = IN_HEADER + self.header.gate + self.header.up; &self.blob[s..s + self.header.down_bytes] } - /// The expert's weights: gate, up and down, which sit between the header and the activations. - pub(super) fn weights(&self) -> &[u8] { - &self.blob[IN_HEADER..self.header.input_at()] - } pub(super) fn input(&self) -> Vec { words_le(&self.blob[self.header.input_at()..]).into_iter().map(f32::from_bits).collect() } 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 0dc51bc8..945b2681 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,10 +1,9 @@ -//! 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; @@ -18,8 +17,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); @@ -58,39 +57,20 @@ pub(super) fn cmd_run_tree( only_case: Option<&str>, ) -> Result { let verified = verify_dir(dir).map_err(|e| e.to_string())?; - pin_process(pin); + 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(); - print_report(&report); + for line in &report { + println!("REPORT {line}"); + } let family = family_of(&report).ok_or("no process kernel family line in cpu_kernel_report")?; if family != tree { eprintln!("kernel_ab: this process runs the {family} family, not {tree}"); return Ok(ExitCode::from(3)); } fs::create_dir_all(out).map_err(|e| format!("{}: {e}", out.display()))?; - let done = write_tree_outputs(&verified, tree, out, only_case)?; - if done == 0 { - return Err(format!("case {} is not in the manifest", only_case.unwrap_or("?"))); - } - println!("RUN-TREE {tree} cases={done}"); - Ok(ExitCode::SUCCESS) -} - -/// Pins the calling thread; a refused pin is reported and the run goes on unpinned. -fn pin_process(pin: usize) { - if rust_topology::pin_current_thread(pin as i32) < 0 { - eprintln!("kernel_ab: the pin to CPU {pin} was refused; running unpinned"); - } -} - -fn print_report(report: &[String]) { - for line in report { - println!("REPORT {line}"); - } -} - -/// Computes the cases (all, or only `only_case`) with a one-worker pool and writes one `.out` file per case; returns -/// how many. -fn write_tree_outputs(verified: &Verified, tree: &str, out: &Path, only_case: Option<&str>) -> Result { 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)) { @@ -99,61 +79,53 @@ fn write_tree_outputs(verified: &Verified, tree: &str, out: &Path, only_case: Op write_out(&out.join(format!("case-{}.rust-{tree}.out", c.id)), c.rows, tree, &values)?; done += 1; } - Ok(done) + if done == 0 { + return Err(format!("case {} is not in the manifest", only_case.unwrap_or("?"))); + } + println!("RUN-TREE {tree} cases={done}"); + Ok(ExitCode::SUCCESS) } + // ------------------------------------------------------------------------------------------------ compare driver -/// Linux: is the SMT sibling of `cpu` idle (below 5 percent busy over 200 ms)? No sibling counts as idle. Elsewhere: -/// false (unknown). +/// 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) = sibling_cpus(cpu) else { return false }; - if siblings.is_empty() { - return true; - } - let before: Vec<_> = siblings.iter().map(|s| jiffies_total_idle(*s)).collect(); - std::thread::sleep(std::time::Duration::from_millis(200)); - siblings.iter().zip(before).all(|(s, b)| stayed_idle(b, jiffies_total_idle(*s))) -} - -/// The other logical CPUs of the core of `cpu` from sysfs; None when the list cannot be read or parsed. -fn sibling_cpus(cpu: usize) -> Option> { - let list = fs::read_to_string(format!("/sys/devices/system/cpu/cpu{cpu}/topology/thread_siblings_list")).ok()?; + let Ok(list) = fs::read_to_string(format!("/sys/devices/system/cpu/cpu{cpu}/topology/thread_siblings_list")) else { + return false; + }; let mut siblings = Vec::new(); for part in list.trim().split(',') { let (a, b) = part.split_once('-').unwrap_or((part, part)); - let (Ok(a), Ok(b)) = (a.trim().parse::(), b.trim().parse::()) else { return None }; + let (Ok(a), Ok(b)) = (a.trim().parse::(), b.trim().parse::()) else { return false }; siblings.extend((a..=b).filter(|s| *s != cpu)); } - Some(siblings) -} - -/// (total, idle) jiffies of one logical CPU from /proc/stat (Linux). -fn jiffies_total_idle(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)) -} - -/// The CPU was below 5 percent busy between the two samples; a missing sample or no elapsed time is not idle. -fn stayed_idle(before: Option<(u64, u64)>, after: Option<(u64, u64)>) -> bool { - match (before, after) { + 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(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, - } + }) } 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]; @@ -202,33 +174,19 @@ pub(super) fn parse_options(args: &[String]) -> Result { }; let mut it = args.iter(); while let Some(a) = it.next() { - if !takes_value(a) { - return Err(format!("unknown option {a}")); + 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}")), } - let value = it.next().cloned().ok_or_else(|| format!("{a} needs a value"))?; - set_option(&mut o, a, value)?; } 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 options of `compare` / `run-tree` that carry a value. -fn takes_value(flag: &str) -> bool { - matches!(flag, "--out" | "--pin" | "--machine-role" | "--trees" | "--tree" | "--case") -} - -/// Stores the value of one option that takes a value (see `takes_value`). -fn set_option(o: &mut Options, flag: &str, value: String) -> Result<(), String> { - match flag { - "--out" => o.out = Some(PathBuf::from(value)), - "--pin" => o.pin = value.parse().map_err(|_| "--pin takes a logical CPU number".to_owned())?, - "--machine-role" => o.machine_role = Some(value), - "--trees" => o.trees = value.split(',').map(str::to_owned).collect(), - "--tree" => o.tree = Some(value), - "--case" => o.case = Some(value), - other => return Err(format!("unknown option {other}")), - } - Ok(()) -} diff --git a/crates/native-cpu-expert/src/cpu_report.rs b/crates/native-cpu-expert/src/cpu_report.rs index edc64cb0..e6899542 100644 --- a/crates/native-cpu-expert/src/cpu_report.rs +++ b/crates/native-cpu-expert/src/cpu_report.rs @@ -1,10 +1,8 @@ -//! Start-up report of the CPUs the expert kernels run on and of the kernel family chosen for them (operator log only, -//! no behaviour). +//! Start-up report of the CPUs the expert kernels run on and of the kernel family chosen for them (operator log only, no behaviour). //! -//! The kernel family (AVX-512 or AVX2) is decided once per process by `rust_simd::dispatch()`. This report probes every -//! logical CPU the process may run on (a thread pinned to it, `cpuid`, `xgetbv`) and groups the identical ones, so a -//! machine with several packages or with unlike cores shows each kind on its own line, and a core that cannot run the -//! chosen family is named. +//! The kernel family (AVX-512 or AVX2) is decided once per process by `rust_simd::dispatch()`. This report probes every logical CPU the +//! process may run on (a thread pinned to it, `cpuid`, `xgetbv`) and groups the identical ones, so a machine with several packages or +//! with unlike cores shows each kind on its own line, and a core that cannot run the chosen family is named. use core::arch::x86_64::{__cpuid, __cpuid_count, _xgetbv}; #[derive(Clone, PartialEq, Eq)] @@ -16,13 +14,8 @@ struct Core { const AVX512_NAMES: [&str; 6] = ["F", "BW", "VL", "DQ", "VBMI", "VNNI"]; -/// The text of the 48 brand bytes of CPUID leaves 0x80000002..=0x80000004: NULs and blanks trimmed at both ends. -fn brand_text(raw: &[u8]) -> String { - String::from_utf8_lossy(raw).trim_matches(|c: char| c == '\0' || c.is_whitespace()).to_owned() -} - -/// The brand string of the CPU the calling thread runs on; empty when the CPU has no brand leaves. -fn read_brand() -> String { +/// The CPU brand string from the extended leaves (empty when the CPU has none). +fn brand_string() -> String { if __cpuid(0x8000_0000).eax < 0x8000_0004 { return String::new(); } @@ -33,41 +26,45 @@ fn read_brand() -> String { raw.extend_from_slice(&w.to_le_bytes()); } } - brand_text(&raw) + String::from_utf8_lossy(&raw).trim_matches(|c: char| c == '\0' || c.is_whitespace()).to_owned() } -/// AVX2, FMA and F16C usable: the CPUID.1 ECX bits, the YMM state enabled in XCR0, the AVX2 bit of leaf 7. -fn has_avx2(c1: u32, xcr0: u64, l7_ebx: u32) -> bool { - [12, 27, 28, 29].iter().all(|b| c1 & (1 << b) != 0) && xcr0 & 6 == 6 && l7_ebx & (1 << 5) != 0 -} - -/// F, BW, VL, DQ, VBMI, VNNI (in `AVX512_NAMES` order) present and the ZMM state enabled by the OS. -fn avx512_flags(osxsave: bool, xcr0: u64, l7_ebx: u32, l7_ecx: u32) -> [bool; 6] { - let os512 = osxsave && xcr0 & 0xe6 == 0xe6; - let bits = [ - l7_ebx & (1 << 16) != 0, - l7_ebx & (1 << 30) != 0, - l7_ebx & (1 << 31) != 0, - l7_ebx & (1 << 17) != 0, - l7_ecx & (1 << 1) != 0, - l7_ecx & (1 << 11) != 0, - ]; - bits.map(|b| b && os512) +/// AVX2/FMA/F16C and the six AVX-512 subsets of the calling core (leaf 7 must exist). +/// +/// # Safety +/// CPUID is always available on x86_64; XGETBV only after the OSXSAVE bit is seen. +unsafe fn feature_bits() -> (bool, [bool; 6]) { + unsafe { + let c1 = __cpuid(1).ecx; + let osxsave = c1 & (1 << 27) != 0; + let xcr0 = if osxsave { _xgetbv(0) } else { 0 }; + let l7 = __cpuid_count(7, 0); + let avx2 = [12, 27, 28, 29].iter().all(|b| c1 & (1 << b) != 0) && xcr0 & 6 == 6 && l7.ebx & (1 << 5) != 0; + let os512 = osxsave && xcr0 & 0xe6 == 0xe6; + let bits = [ + l7.ebx & (1 << 16) != 0, + l7.ebx & (1 << 30) != 0, + l7.ebx & (1 << 31) != 0, + l7.ebx & (1 << 17) != 0, + l7.ecx & (1 << 1) != 0, + l7.ecx & (1 << 11) != 0, + ]; + (avx2, bits.map(|b| b && os512)) + } } /// The features of the core the calling thread runs on. The gates mirror `rust_simd::probe_avx2` / `probe_avx512`. fn probe() -> Core { - let max = __cpuid(0).eax; - let brand = read_brand(); - if max < 7 { - return Core { brand, avx2: false, avx512: [false; 6] }; + // SAFETY: CPUID is always available on x86_64; XGETBV only after the OSXSAVE bit is seen. + unsafe { + let max = __cpuid(0).eax; + let brand = brand_string(); + if max < 7 { + return Core { brand, avx2: false, avx512: [false; 6] }; + } + let (avx2, avx512) = feature_bits(); + Core { brand, avx2, avx512 } } - let c1 = __cpuid(1).ecx; - let osxsave = c1 & (1 << 27) != 0; - // SAFETY: XGETBV only after the OSXSAVE bit is seen. - let xcr0 = if osxsave { unsafe { _xgetbv(0) } } else { 0 }; - let l7 = __cpuid_count(7, 0); - Core { brand, avx2: has_avx2(c1, xcr0, l7.ebx), avx512: avx512_flags(osxsave, xcr0, l7.ebx, l7.ecx) } } fn avx512_complete(c: &Core) -> bool { @@ -92,39 +89,30 @@ fn ranges(cpus: &[usize]) -> String { out } -/// A pinned probe thread for logical CPU `cpu`; a refused pin probes wherever the thread runs (the line then shows -/// that CPU kind). `None` when the probe thread panicked. -fn probe_pinned(cpu: usize) -> Option { - std::thread::spawn(move || { - let previous = crate::rust_topology::pin_current_thread(cpu as i32); - let core = probe(); - crate::rust_topology::restore_thread_affinity(previous); - core - }) - .join() - .ok() -} - -/// Adds `cpu` to the group of identical cores `core` belongs to, or starts a new group. -fn push_group(groups: &mut Vec<(Core, Vec)>, core: Core, cpu: usize) { - match groups.iter_mut().find(|(g, _)| *g == core) { - Some((_, cpus)) => cpus.push(cpu), - None => groups.push((core, vec![cpu])), - } -} - -/// Every logical CPU the process may run on (at most 256), probed on its own thread and grouped by identical features. +/// The logical CPUs the process may run on, grouped by identical probe result (first-seen order). fn probe_groups() -> Vec<(Core, Vec)> { let n = std::thread::available_parallelism().map_or(1, |n| n.get()).min(256); let mut groups: Vec<(Core, Vec)> = Vec::new(); for cpu in 0..n { - let Some(core) = probe_pinned(cpu) else { continue }; - push_group(&mut groups, core, cpu); + // a pinned probe thread per logical CPU; a refused pin probes wherever the thread runs (the line then shows + // that CPU's kind) + let core = std::thread::spawn(move || { + let previous = crate::rust_topology::pin_current_thread(cpu as i32); + let core = probe(); + crate::rust_topology::restore_thread_affinity(previous); + core + }) + .join(); + let Ok(core) = core else { continue }; + match groups.iter_mut().find(|(g, _)| *g == core) { + Some((_, cpus)) => cpus.push(cpu), + None => groups.push((core, vec![cpu])), + } } groups } -/// The AVX-512 part of a core line: all of the six extensions, none, or which ones the core has and lacks. +/// The AVX-512 part of a core line: all, none, or which subsets it has and lacks. fn avx512_summary(core: &Core) -> String { let have: Vec<&str> = AVX512_NAMES.iter().zip(core.avx512).filter(|(_, b)| *b).map(|(n, _)| *n).collect(); let lacks: Vec<&str> = AVX512_NAMES.iter().zip(core.avx512).filter(|(_, b)| !*b).map(|(n, _)| *n).collect(); @@ -137,18 +125,7 @@ fn avx512_summary(core: &Core) -> String { } } -/// The kernel family the core itself can run. -fn core_family(core: &Core) -> &'static str { - if avx512_complete(core) { - "AVX-512" - } else if core.avx2 { - "AVX2" - } else { - "none (unsupported)" - } -} - -/// The line of one group of identical logical CPUs. +/// The report line of one group of identical logical CPUs. fn core_line(core: &Core, cpus: &[usize]) -> String { format!( "cpu: logical {} ({}): {}; AVX2/FMA/F16C: {}; {}; kernel family on this core: {}", @@ -157,23 +134,24 @@ fn core_line(core: &Core, cpus: &[usize]) -> String { if core.brand.is_empty() { "unknown model" } else { &core.brand }, if core.avx2 { "yes" } else { "no" }, avx512_summary(core), - core_family(core) + if avx512_complete(core) { + "AVX-512" + } else if core.avx2 { + "AVX2" + } else { + "none (unsupported)" + } ) } -/// The environment switches that change the kernel family, in the order they are reported. -fn family_switches() -> Vec<&'static str> { +/// The line with the kernel family the process chose and the environment switches that changed it. +fn process_line(dispatch: &crate::rust_simd::Dispatch) -> String { let mut switches = Vec::new(); for name in ["STRATA_FORCE_AVX2", "STRATA_NO_IQ512", "STRATA_NO_IQ256", "STRATA_NO_IQ4NL"] { if std::env::var_os(name).is_some() { switches.push(name); } } - switches -} - -/// The line with the kernel family the process chose and the switches that changed it. -fn process_line(dispatch: &crate::rust_simd::Dispatch, switches: &[&str]) -> String { format!( "cpu: process kernel family {} (IQ rows: 512-bit {}, 256-bit {}; IQ4_NL {}){}", if dispatch.avx512 { "AVX-512" } else { "AVX2" }, @@ -184,27 +162,22 @@ fn process_line(dispatch: &crate::rust_simd::Dispatch, switches: &[&str]) -> Str ) } -/// True when some group disagrees with the process family in a way that matters: the process uses AVX-512 and the -/// group lacks it, or the group has all of it and the process does not use it. -fn differs_in_avx512(groups: &[(Core, Vec)], dispatch: &crate::rust_simd::Dispatch) -> bool { - groups.len() > 1 - && groups.iter().any(|(c, _)| avx512_complete(c) != dispatch.avx512 && (dispatch.avx512 || avx512_complete(c))) -} - -const MIXED_AVX512_WARNING: &str = concat!( - "cpu: WARNING: the logical CPUs differ in AVX-512 support but the kernel family is chosen once per process; ", - "a worker pinned to a core without it would fault or be refused" -); - -/// One line per kind of logical CPU, then one line with the kernel family the process chose and the switches that -/// changed it. +/// One line per kind of logical CPU, then one line with the kernel family the process chose and the switches that changed it. pub fn cpu_kernel_report() -> Vec { let groups = probe_groups(); let mut lines: Vec = groups.iter().map(|(core, cpus)| core_line(core, cpus)).collect(); let dispatch = crate::rust_simd::dispatch(); - lines.push(process_line(dispatch, &family_switches())); - if differs_in_avx512(&groups, dispatch) { - lines.push(MIXED_AVX512_WARNING.to_owned()); + lines.push(process_line(dispatch)); + if groups.len() > 1 + && groups.iter().any(|(c, _)| avx512_complete(c) != dispatch.avx512 && (dispatch.avx512 || avx512_complete(c))) + { + lines.push( + concat!( + "cpu: WARNING: the logical CPUs differ in AVX-512 support but the kernel family is chosen once per ", + "process; a worker pinned to a core without it would fault or be refused" + ) + .to_owned(), + ); } lines } diff --git a/crates/native-cpu-expert/src/impl_cpupool.rs b/crates/native-cpu-expert/src/impl_cpupool.rs index a497e1ca..f81a93d3 100644 --- a/crates/native-cpu-expert/src/impl_cpupool.rs +++ b/crates/native-cpu-expert/src/impl_cpupool.rs @@ -1,11 +1,11 @@ -//! Moved out of the parent module by STRA-338: CpuPool, PendingBatch and their Drop impls. +//! Moved out of the parent module by STRA-338: impl CpuPool, impl PendingBatch, impl Drop_for_PendingBatch, impl Drop_for_CpuPool. #[allow(unused_imports)] use super::*; -/// The coordinator thread: creates the native pool, reports its worker count (or the error) to `startup`, then serves -/// batches until the command channel closes. -fn run_coordinator( +/// The actor thread: build the native pool, report its worker count (or the failure), then serve batches until the +/// command channel closes or a native failure closes the coordinator. +fn actor_main( workers: i32, receive: mpsc::Receiver>, send_result: mpsc::SyncSender>>, @@ -22,15 +22,14 @@ fn run_coordinator( if startup.send(native.workers()).is_err() { return; } - serve_batches(native, &receive, &send_result); + serve(native, receive, send_result); } - -/// Computes every received batch and sends it back, until the actor closes the channel, drops the result channel, or a -/// native failure closes the coordinator for good. -fn serve_batches( +/// Compute received batches until the command channel closes, the result channel closes or a native failure closes the +/// coordinator forever. +fn serve( mut native: ffi::NativePool, - receive: &mpsc::Receiver>, - send_result: &mpsc::SyncSender>>, + receive: mpsc::Receiver>, + send_result: mpsc::SyncSender>>, ) { while let Ok(mut jobs) = receive.recv() { let result = native.compute_batch(&mut jobs); @@ -50,35 +49,6 @@ fn serve_batches( } // NativePool is destroyed here; original destructor joins all workers. } - -/// The result vector of a batch of `jobs` once the jobs are admitted: 1..=MAX_JOBS jobs in a vector of at most that -/// capacity, within `allowance` and the batch ceiling. `Shape`, `BudgetExceeded` or `Allocation` otherwise. -fn admit_batch(jobs: &Vec, allowance: usize) -> Result> { - if !(1..=MAX_JOBS).contains(&jobs.len()) || jobs.capacity() > MAX_JOBS { - return Err(Error::Shape); - } - if allowance > MAX_BATCH_BYTES { - return Err(Error::BudgetExceeded); - } - let mut results = Vec::new(); - results.try_reserve_exact(jobs.len()).map_err(|_| Error::Allocation)?; - if batch_charge(jobs, &results)? > allowance { - return Err(Error::BudgetExceeded); - } - Ok(results) -} - -/// The bytes a batch is charged: the metadata of the job and result vectors plus the bytes every job owns. -fn batch_charge(jobs: &Vec, results: &Vec) -> Result { - let results_bytes = results.capacity().checked_mul(std::mem::size_of::()); - let metadata = jobs - .capacity() - .checked_mul(std::mem::size_of::()) - .and_then(|n| results_bytes.and_then(|m| n.checked_add(m))) - .ok_or(Error::BudgetExceeded)?; - jobs.iter().try_fold(metadata, |bytes, job| bytes.checked_add(job.owned_bytes()?).ok_or(Error::BudgetExceeded)) -} - impl CpuPool { pub fn new(workers: i32) -> Result { let (command, receive) = mpsc::sync_channel::>(1); @@ -87,7 +57,7 @@ impl CpuPool { let worker = thread::Builder::new() .name("leleka-cpu-miss".into()) .stack_size(2 * 1024 * 1024) - .spawn(move || run_coordinator(workers, receive, send_result, startup)) + .spawn(move || actor_main(workers, receive, send_result, startup)) .map_err(|_| Error::Allocation)?; match initialized.recv().unwrap_or(Err(Error::NativeFailure)) { Ok(workers) => Ok(Self { @@ -109,11 +79,34 @@ impl CpuPool { pub fn workers(&self) -> usize { self.workers } - pub fn start(&mut self, jobs: Vec, allowance: usize) -> Result> { + /// Bytes a batch is charged: the job and result vectors' capacity plus every job's owned bytes. + fn charged_bytes(jobs: &[PreparedJob], (jobs_cap, results_cap): (usize, usize)) -> Result { + let metadata = jobs_cap + .checked_mul(std::mem::size_of::()) + .and_then(|n| results_cap.checked_mul(std::mem::size_of::()).and_then(|m| n.checked_add(m))) + .ok_or(Error::BudgetExceeded)?; + jobs.iter().try_fold(metadata, |bytes, job| bytes.checked_add(job.owned_bytes()?).ok_or(Error::BudgetExceeded)) + } + /// The pool is open and idle, and the batch has an admissible size and byte allowance. + fn admit(&self, jobs: &Vec, allowance: usize) -> Result<()> { if self.failed || self.in_flight { return Err(Error::Closed); } - let results = admit_batch(&jobs, allowance)?; + if !(1..=MAX_JOBS).contains(&jobs.len()) || jobs.capacity() > MAX_JOBS { + return Err(Error::Shape); + } + if allowance > MAX_BATCH_BYTES { + return Err(Error::BudgetExceeded); + } + Ok(()) + } + pub fn start(&mut self, jobs: Vec, allowance: usize) -> Result> { + self.admit(&jobs, allowance)?; + let mut results = Vec::new(); + results.try_reserve_exact(jobs.len()).map_err(|_| Error::Allocation)?; + if Self::charged_bytes(&jobs, (jobs.capacity(), results.capacity()))? > allowance { + return Err(Error::BudgetExceeded); + } if self.command.as_ref().ok_or(Error::Closed)?.send(jobs).is_err() { self.failed = true; return Err(Error::Closed); diff --git a/crates/native-cpu-expert/src/impl_gateupformat.rs b/crates/native-cpu-expert/src/impl_gateupformat.rs index bff6b439..2f95edc1 100644 --- a/crates/native-cpu-expert/src/impl_gateupformat.rs +++ b/crates/native-cpu-expert/src/impl_gateupformat.rs @@ -1,4 +1,4 @@ -//! Moved out of the parent module by STRA-338: the format tables, PreparedJob, DirectCpuPool and CompletedJob. +//! Moved out of the parent module by STRA-338: impl GateUpFormat, impl DownFormat, impl PreparedJob, impl DirectCpuPool, impl Drop_for_DirectCpuPool, impl CompletedJob. #[allow(unused_imports)] use super::*; @@ -15,6 +15,11 @@ impl GateUpFormat { Self::Iq2Xs => 17, } } + /// Bytes of one gate or up matrix (`FF` rows of `H` weights) and the bytes per block. + pub(super) fn matrix_bytes(self) -> (usize, usize) { + let (q, b) = self.block(); + (H / q * b * FF, b) + } pub(super) fn block(self) -> (usize, usize) { match self { Self::Iq3Xxs => (256, 98), @@ -34,6 +39,11 @@ impl DownFormat { Self::Q2_0 => 42, } } + /// Bytes of the down matrix (`H` rows of `FF` weights) and the bytes per block. + pub(super) fn matrix_bytes(self) -> (usize, usize) { + let (q, b) = self.block(); + (FF / q * b * H, b) + } pub(super) fn block(self) -> (usize, usize) { match self { Self::Iq4Nl => (32, 18), @@ -41,42 +51,8 @@ impl DownFormat { } } } -/// `NonFinite` when any block of the three role matrices starts with an FP16 header that is Inf or NaN. -/// -/// Every admitted family has one FP16 header at each original block start. Integer multipliers are bounded; this is a -/// guard, never a source proof. -fn validate_headers(roles: [(&[u8], usize); 3]) -> Result<()> { - for (bytes, block) in roles { - for at in (0..bytes.len()).step_by(block) { - if u16::from_le_bytes([bytes[at], bytes[at + 1]]) & 0x7c00 == 0x7c00 { - return Err(Error::NonFinite); - } - } - } - Ok(()) -} - -/// The complete native G|U|D owner: the three role matrices copied one after the other into one fallible allocation. -fn join_blob(gate: &[u8], up: &[u8], down: &[u8], gsize: usize, dsize: usize) -> Result> { - let size = gsize.checked_mul(2).and_then(|n| n.checked_add(dsize)).ok_or(Error::Shape)?; - let mut blob = Vec::new(); - blob.try_reserve_exact(size).map_err(|_| Error::Allocation)?; - blob.extend_from_slice(gate); - blob.extend_from_slice(up); - blob.extend_from_slice(down); - Ok(blob.into_boxed_slice()) -} - -/// `rows * H` zeroed output floats in one fallible allocation. -fn zeroed_output(rows: usize) -> Result> { - let mut output = Vec::new(); - output.try_reserve_exact(rows * H).map_err(|_| Error::Allocation)?; - output.resize(rows * H, 0.0); - Ok(output.into_boxed_slice()) -} - -/// The rows and the input of a job: 1..=MAX_ROWS rows of `H` finite floats. -fn validate_input(input: &[f32], rows: usize) -> Result<()> { +/// Row count in range, one `H`-float input row per job row, every input finite. +fn check_job_input(rows: usize, input: &[f32]) -> Result<()> { if !(1..=MAX_ROWS).contains(&rows) || input.len() != rows * H { return Err(Error::Shape); } @@ -85,14 +61,41 @@ fn validate_input(input: &[f32], rows: usize) -> Result<()> { } Ok(()) } - -/// The block (values, bytes) of the gate/up and down formats and the byte sizes of one gate/up and the down matrix. -fn matrix_sizes(gu: GateUpFormat, down: DownFormat) -> ((usize, usize), (usize, usize), usize, usize) { - let (gq, gb) = gu.block(); - let (dq, db) = down.block(); - ((gq, gb), (dq, db), H / gq * gb * FF, FF / dq * db * H) +// Every admitted family has one FP16 header at each original block start. +// Integer multipliers are bounded; this is a guard, never a source proof. +fn check_fp16_headers(parts: [(&[u8], usize); 3]) -> Result<()> { + for (bytes, block) in parts { + for at in (0..bytes.len()).step_by(block) { + if u16::from_le_bytes([bytes[at], bytes[at + 1]]) & 0x7c00 == 0x7c00 { + return Err(Error::NonFinite); + } + } + } + Ok(()) +} +/// The gate/up and down matrices concatenated into one immutable G|U|D owner; the role owners are dropped before +/// the caller allocates its output. +fn concat_blob(gate: Box<[u8]>, up: Box<[u8]>, down: Box<[u8]>, (gsize, dsize): (usize, usize)) -> Result> { + let size = gsize.checked_mul(2).and_then(|n| n.checked_add(dsize)).ok_or(Error::Shape)?; + let mut blob = Vec::new(); + blob.try_reserve_exact(size).map_err(|_| Error::Allocation)?; + blob.extend_from_slice(&gate); + blob.extend_from_slice(&up); + blob.extend_from_slice(&down); + // Drop original role owners before output allocation; all numerical + // consumers will use this immutable complete native G|U|D owner. + drop(gate); + drop(up); + drop(down); + Ok(blob.into_boxed_slice()) +} +/// `len` zeroed output floats. +fn zeroed_output(len: usize) -> Result> { + let mut output = Vec::new(); + output.try_reserve_exact(len).map_err(|_| Error::Allocation)?; + output.resize(len, 0.0); + Ok(output.into_boxed_slice()) } - impl PreparedJob { pub fn new( gu: GateUpFormat, @@ -103,19 +106,15 @@ impl PreparedJob { input: Box<[f32]>, rows: usize, ) -> Result { - validate_input(&input, rows)?; - let ((_, gb), (_, db), gsize, dsize) = matrix_sizes(gu, down); + check_job_input(rows, &input)?; + let (gsize, gb) = gu.matrix_bytes(); + let (dsize, db) = down.matrix_bytes(); if gate.len() != gsize || up.len() != gsize || down_bytes.len() != dsize { return Err(Error::Shape); } - validate_headers([(&gate[..], gb), (&up[..], gb), (&down_bytes[..], db)])?; - let blob = join_blob(&gate, &up, &down_bytes, gsize, dsize)?; - // Drop original role owners before output allocation; all numerical - // consumers will use this immutable complete native G|U|D owner. - drop(gate); - drop(up); - drop(down_bytes); - let output = zeroed_output(rows)?; + check_fp16_headers([(&gate, gb), (&up, gb), (&down_bytes, db)])?; + let blob = concat_blob(gate, up, down_bytes, (gsize, dsize))?; + let output = zeroed_output(rows * H)?; Ok(Self { gu, down, gate_bytes: gsize, up_bytes: gsize, down_bytes: dsize, rows, blob, input, output }) } pub fn owned_bytes(&self) -> Result { @@ -147,8 +146,7 @@ impl DirectCpuPool { pub fn workers(&self) -> usize { self.workers } - /// `LELEKA_POOL_TIMING=1`: the host stage times of `compute_group` summed since the last call, in ms (see - /// `POOL_TIMING_STAGES`). + /// `LELEKA_POOL_TIMING=1`: the host's stage times of `compute_group` summed since the last call, in ms (see `POOL_TIMING_STAGES`). pub fn take_timing(&mut self) -> Option<[f64; POOL_TIMING_STAGES]> { self.native.take_timing() } diff --git a/crates/native-cpu-expert/src/pool_plan.rs b/crates/native-cpu-expert/src/pool_plan.rs index 27e37a40..c3d2ed4a 100644 --- a/crates/native-cpu-expert/src/pool_plan.rs +++ b/crates/native-cpu-expert/src/pool_plan.rs @@ -1,21 +1,16 @@ -//! How many CPU expert workers to start by default (docs/upstream-port-plan.md row 2.3; upstream `pool_plan.hpp`, -//! commit `5ece068f`). +//! How many CPU expert workers to start by default (docs/upstream-port-plan.md row 2.3; upstream `pool_plan.hpp`, commit `5ece068f`). //! -//! Pure arithmetic on a CPU description, unit tested on mock CPUs. The plan is opt-in (`LELEKA_CPU_POOL_PLAN=on`): the -//! default of the stack stays the Original's 15 until the plan has a paired A/B on the machine it changes. On the -//! 16-core 9950X3D of the server the plan gives 15 as well. +//! Pure arithmetic on a CPU description, unit tested on mock CPUs. The plan is opt-in (`LELEKA_CPU_POOL_PLAN=on`): the stack's default stays the +//! Original's 15 until the plan has a paired A/B on the machine it changes. On the 16-core 9950X3D of the server the plan gives 15 as well. //! -//! Why a plan and not "every physical core but the host's": the workers of the pool spin while they wait, so a worker -//! without a core of its own takes cycles from one that has one (a bigger count is slower, not just useless); the -//! kernel is DRAM-bound, past the width of the memory system more cores add nothing and the barrier at the end of -//! every layer waits for more threads; a container limited by a CFS quota still shows every core of the machine. The -//! pool refuses more than 15 workers (`NativePool::new`), so the count handed to the pool is also capped at -//! [`POOL_MAX_WORKERS`]. +//! Why a plan and not "every physical core but the host's": the pool's workers spin while they wait, so a worker without a core of its own takes +//! cycles from one that has one (a bigger count is slower, not just useless); the kernel is DRAM-bound, past the memory system's width more cores +//! add nothing and the barrier at the end of every layer waits for more threads; a container limited by a CFS quota still shows every core of the +//! machine. The pool refuses more than 15 workers (`NativePool::new`), so the count handed to the pool is also capped at [`POOL_MAX_WORKERS`]. /// The pool's own ceiling (`NativePool::new` refuses more). pub const POOL_MAX_WORKERS: usize = 15; -/// Upstream measured cap of a default count (`kPoolWorkersCap`); above the ceiling of the pool here, kept so the -/// mock-CPU tests match upstream. +/// Upstream's measured cap of a default count (`kPoolWorkersCap`); above the pool's ceiling here, kept so the mock-CPU tests match upstream's. pub const WORKERS_CAP: usize = 32; /// A CPU with at least this many workers keeps [`RESERVE`] cores free for the engine's other threads. pub const RESERVE_FROM: usize = 16; @@ -26,8 +21,7 @@ pub const RESERVE: usize = 1; pub struct PoolPlanInput { /// Logical processors this process may run on. pub logical: usize, - /// Physical cores this process may use per CPU package, the package of the host thread first (its own core is - /// counted); empty = unknown. + /// Physical cores this process may use per CPU package, the host thread's package first (its own core is counted); empty = unknown. pub cores_per_package: Vec, /// CPUs a container quota allows (cgroup `cpu.max`); 0 = no quota. pub cpu_quota: f64, @@ -49,90 +43,75 @@ pub struct PoolPlan { pub limit: &'static str, } -/// The core layout the plan counts: physical cores (all packages and the host package), packages, and whether the OS -/// said which logical processors share a core. -struct Layout { - cores: usize, - local: usize, - packages: usize, - known: bool, -} - -/// The worker count so far and what bounded it (for the start-up line). +/// A worker count and what bounded it. #[derive(Clone, Copy)] struct Bound { n: usize, limit: &'static str, } -impl Bound { - /// The bound lowered to `candidate` (named `limit`) when that is below the count so far, else unchanged. - fn lowered_to(self, candidate: usize, limit: &'static str) -> Self { - if candidate < self.n { Self { n: candidate, limit } } else { self } - } -} - -fn read_layout(input: &PoolPlanInput) -> Layout { - let cores: usize = input.cores_per_package.iter().sum(); - let local = input.cores_per_package.first().copied().unwrap_or(0); +/// Physical cores counted, those of the host's package, the package count and whether the layout was known. +fn core_layout(input: &PoolPlanInput) -> (usize, usize, usize, bool) { + let mut cores: usize = input.cores_per_package.iter().sum(); + let mut local = input.cores_per_package.first().copied().unwrap_or(0); let packages = input.cores_per_package.len().max(1); let known = !input.cores_per_package.is_empty() && cores > 0; - if known { - return Layout { cores, local, packages, known }; + if !known { + // The OS did not say which logical processors share a core: counting every one as a core is what put a + // 256-thread machine at 255 workers. + cores = if input.logical >= 16 { input.logical / 2 } else { input.logical }; + local = cores; } - // The OS did not say which logical processors share a core: counting every one as a core is what put a 256-thread - // machine at 255 workers. - let cores = if input.logical >= 16 { input.logical / 2 } else { input.logical }; - Layout { cores, local: cores, packages, known } + (cores, local, packages, known) } -/// Every physical core but the host first (the host thread has the first core), bounded by the socket of the host. -fn host_bound(layout: &Layout) -> Bound { - let n = layout.local.saturating_sub(1).max(1); - let limit = if !layout.known { - "half the logical processors (the OS gave no core layout)" - } else if layout.packages > 1 { - "the host's CPU socket" - } else { - "every physical core but the host's" - }; +/// Every physical core of the host's package but the host's, minus the reserve on a big CPU. +fn base_bound(local: usize, packages: usize, known: bool) -> Bound { + let mut limit = "every physical core but the host's"; + let mut n = local.saturating_sub(1).max(1); // the host thread has the first core + if !known { + limit = "half the logical processors (the OS gave no core layout)"; + } else if packages > 1 { + limit = "the host's CPU socket"; + } + if n >= RESERVE_FROM { + n -= RESERVE; + if known && packages == 1 { + limit = "physical cores, one kept free"; + } + } Bound { n, limit } } -/// A CPU with at least `RESERVE_FROM` workers keeps `RESERVE` cores free for the other threads of the engine. -fn keep_cores_free(bound: Bound, layout: &Layout) -> Bound { - if bound.n < RESERVE_FROM { - return bound; - } - let limit = if layout.known && layout.packages == 1 { "physical cores, one kept free" } else { bound.limit }; - Bound { n: bound.n - RESERVE, limit } -} - /// A hybrid CPU with more E-cores than P-cores: the P-cores but the host's plus half of the E-cores. -fn hybrid_workers(input: &PoolPlanInput) -> Option { - (input.p_cores > 0 && input.e_cores > input.p_cores).then(|| (input.p_cores - 1 + input.e_cores / 2).max(1)) +fn cap_hybrid(input: &PoolPlanInput, b: Bound) -> Bound { + if input.p_cores > 0 && input.e_cores > input.p_cores { + let h = (input.p_cores - 1 + input.e_cores / 2).max(1); + if h < b.n { + return Bound { n: h, limit: "the performance cores and half of the efficiency cores" }; + } + } + b } -/// The CPUs a container quota allows, less the host, at least one. -fn quota_workers(input: &PoolPlanInput) -> Option { - (input.cpu_quota > 0.0).then(|| ((input.cpu_quota as usize).saturating_sub(1)).max(1)) +/// A container CPU quota below the count. +fn cap_quota(input: &PoolPlanInput, b: Bound) -> Bound { + if input.cpu_quota > 0.0 { + let q = ((input.cpu_quota as usize).saturating_sub(1)).max(1); + if q < b.n { + return Bound { n: q, limit: "the container's CPU quota" }; + } + } + b } pub fn plan_pool_workers(input: &PoolPlanInput) -> PoolPlan { - let layout = read_layout(input); - let bound = keep_cores_free(host_bound(&layout), &layout); - let bound = hybrid_workers(input) - .map_or(bound, |h| bound.lowered_to(h, "the performance cores and half of the efficiency cores")); - let bound = quota_workers(input).map_or(bound, |q| bound.lowered_to(q, "the container's CPU quota")); - let bound = bound.lowered_to(WORKERS_CAP, "the measured cap"); - PoolPlan { - workers: bound.n.max(1), - cores: layout.cores, - cores_local: layout.local, - packages: layout.packages, - topology_known: layout.known, - limit: bound.limit, + let (cores, local, packages, known) = core_layout(input); + let mut b = cap_quota(input, cap_hybrid(input, base_bound(local, packages, known))); + if b.n > WORKERS_CAP { + b = Bound { n: WORKERS_CAP, limit: "the measured cap" }; } + PoolPlan { workers: b.n.max(1), cores, cores_local: local, packages, topology_known: known, limit: b.limit } } /// The CPU this process runs on, as far as this build can read it. diff --git a/crates/native-cpu-expert/src/rust_bench.rs b/crates/native-cpu-expert/src/rust_bench.rs index 2fba887b..f8137367 100644 --- a/crates/native-cpu-expert/src/rust_bench.rs +++ b/crates/native-cpu-expert/src/rust_bench.rs @@ -107,20 +107,6 @@ pub struct DequantizedExpert { pub up: Vec, pub down: Vec, } -/// Dequantizes `rows` rows of `width` values of one role; its blob rows start at `offset`, `stride` bytes apart. -fn dequantize_role( - kind: Kind, - blob: &[u8], - (offset, stride): (usize, usize), - (rows, width): (usize, usize), - out: &mut [f32], -) -> Result<()> { - for r in 0..rows { - let raw = &blob[offset + r * stride..offset + (r + 1) * stride]; - super::rust_dequant::dequantize(kind, raw, &mut out[r * width..(r + 1) * width])?; - } - Ok(()) -} pub fn dequantize_expert(f: &NativeFormat, blob: &[u8]) -> Result { f.validate()?; if blob.len() != f.bytes { @@ -130,29 +116,27 @@ pub fn dequantize_expert(f: &NativeFormat, blob: &[u8]) -> Result f32 { - let (mut g, mut u) = (0.0f64, 0.0f64); - for (i, &x) in x.iter().enumerate() { - g += w.gate[r * n_embd + i] as f64 * x as f64; - u += w.up[r * n_embd + i] as f64 * x as f64; - } - (g / (1.0 + (-g).exp()) * u) as f32 -} -/// Down row `r` . hidden, accumulated in f64. -fn down_unit(w: &DequantizedExpert, n_ff: usize, r: usize, hidden: &[f32]) -> f32 { - let mut value = 0.0f64; - for (i, &h) in hidden.iter().enumerate() { - value += w.down[r * n_ff + i] as f64 * h as f64; - } - value as f32 -} pub fn float_oracle(f: &NativeFormat, blob: &[u8], input: &[f32]) -> Result> { f.validate()?; if input.is_empty() || input.len() % f.n_embd != 0 { @@ -163,35 +147,23 @@ pub fn float_oracle(f: &NativeFormat, blob: &[u8], input: &[f32]) -> Result