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 49a885d8..a6cbbfe0 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,15 +3,86 @@ #[allow(unused_imports)] use super::*; -/// `kernel_ab time ...`: one fresh process, one case, the resident and the streamed regime, JSON written by tmp + -/// rename. Exit codes as -/// `kab time`: 0 ok; 1 usage / refused input; 3 a regime kept no slice or a slice migrated off the pin; 4 the final -/// output differs. -pub(super) fn cmd_time(args: &[String]) -> Result { - let t = parse_time_args(args)?; - let wall0 = mono_ns(); - // pin first (before any buffer or pool exists, so the pool's threads inherit the mask), then the facts about the - // pin +mod doc; + +/// What the pinned CPU looked like before the run (read from sysfs and /proc, Linux only). +struct PinStart { + cpu_dir: String, + sib_text: String, + sibling: Option, + sib0: Option<(u64, u64)>, + pin0: Option<(u64, u64)>, + load0: String, +} + +/// What it looked like after the run, and the threads of the process with the CPU each last ran on. +struct PinEnd { + threads: Vec<(String, Option)>, + sib1: Option<(u64, u64)>, + pin1: Option<(u64, u64)>, +} + +/// The case of the run directory: the manifest hash, its entry and the verified input. +struct LoadedCase { + manifest_sha: String, + entry: CaseEntry, + case: CaseIn, +} + +impl LoadedCase { + /// The bytes of one expert (gate, up and down weights). + fn expert_bytes(&self) -> usize { + self.case.header.input_at() - IN_HEADER + } +} + +/// The managed environment, the kernel report and the tree of this process. +struct HostInfo { + env: BTreeMap, + report: Vec, + tree: &'static str, +} + +/// The streamed set: K copies, K x stride at least 2 x the last-level cache of the pinned CPU (the design choice of +/// kab_time.cpp). +struct StreamPlan { + llc: Llc, + stride: usize, + copies_k: usize, +} + +/// Everything known before the first timed call. +struct TimeRun<'a> { + args: &'a [String], + t: TimeArgs, + wall0: u64, + start: PinStart, + loaded: LoadedCase, + host: HostInfo, + plan: StreamPlan, +} + +/// The timed regimes: JSON of each, whether all are ok, and the kept slices of the two regimes. +struct RegimeResults { + json: Vec, + all_ok: bool, + kept_res: usize, + kept_stm: usize, +} + +/// What the timed calls found. +struct Measured { + selfcheck: bool, + regimes: RegimeResults, + ghz: (f64, f64), + final_same: bool, + output_sha: String, +} + +/// Pins the process to `t.pin` before any buffer or pool exists (so the pool's threads inherit the mask), then reads +/// the +/// facts about the pin. +fn pin_and_probe(t: &TimeArgs) -> Result { if rust_topology::pin_current_thread(t.pin as i32) < 0 { return Err(format!("the pin to CPU {} was refused", t.pin)); } @@ -24,24 +95,30 @@ pub(super) fn cmd_time(args: &[String]) -> Result { let sib0 = sibling.and_then(proc_stat_cpu); let pin0 = proc_stat_cpu(t.pin); let load0 = read_text("/proc/loadavg"); + Ok(PinStart { cpu_dir, sib_text, sibling, sib0, pin0, load0 }) +} - // the case: the KAB1 reader rule (validate, then use) and the manifest and case input hashes +/// The case: the KAB1 reader rule (validate, then use) and the manifest and case input hashes. +fn load_case(t: &TimeArgs) -> Result { let (manifest_bytes, _provenance, cases, _files) = read_manifest(&t.dir).map_err(|e| e.to_string())?; let manifest_sha = sha_hex(&manifest_bytes); let entry = cases.iter().find(|c| c.id == t.case).ok_or_else(|| format!("case {} is not in the manifest", t.case))?; - let case = read_case_in(&t.dir, entry).map_err(|e| e.to_string())?; - let header = case.header; - let weights = &case.blob[IN_HEADER..header.input_at()]; - let expert_bytes = weights.len(); + let entry = entry.clone(); + let case = read_case_in(&t.dir, &entry).map_err(|e| e.to_string())?; + Ok(LoadedCase { manifest_sha, entry, case }) +} - // environment and tree +/// The environment and the tree of this process. +fn host_info() -> Result { let env = managed_env_now(); let report = cpu_kernel_report(); let tree = family_of(&report).ok_or("no process kernel family line in cpu_kernel_report")?; + Ok(HostInfo { env, report, tree }) +} - // the streamed set: K copies, K x stride at least 2 x the last-level cache of the pinned CPU (the design choice of - // kab_time.cpp) +/// The last-level cache of the pinned CPU: the override of `--llc-bytes`, else sysfs. +fn llc_for(t: &TimeArgs) -> Result { let llc = match (t.llc_bytes, llc_of_cpu(t.pin)) { (Some(bytes), found) => { Llc { level: found.map_or(0, |l| l.level), bytes, source: "--llc-bytes (override)".to_owned() } @@ -54,223 +131,210 @@ pub(super) fn cmd_time(args: &[String]) -> Result { if llc.bytes == 0 { return Err("--llc-bytes must be positive".to_owned()); } + Ok(llc) +} + +fn plan_stream(t: &TimeArgs, expert_bytes: usize) -> Result { + let llc = llc_for(t)?; let stride = expert_bytes.div_ceil(ALIGN) * ALIGN; let copies_k = ((2 * llc.bytes) / stride as u64) as usize + 1; if copies_k * stride > (4usize << 30) { return Err("the streamed working set would exceed 4 GiB; check --llc-bytes".to_owned()); } + Ok(StreamPlan { llc, stride, copies_k }) +} - // the pool is created AFTER the pin: its worker inherits the one-CPU mask (rust_platform::cores sees a one-CPU - // affinity) - let mut pool = DirectCpuPool::new(1).map_err(|e| format!("DirectCpuPool::new(1) failed: {e:?}"))?; - let want = compute_case(&mut pool, &case)?; - let want_bits: Vec = want.iter().map(|v| v.to_bits()).collect(); - let output_sha = f32_bits_sha(&want); - - let mut tokens = Arena::::new(header.rows * H); - tokens.slice_mut(header.rows * H).copy_from_slice(&case.input()); - let mut resident = Arena::::new(stride); - resident.slice_mut(expert_bytes).copy_from_slice(weights); - let mut streamed = Arena::::new(stride * copies_k); - for k in 0..copies_k { - streamed.slice_mut(stride * copies_k)[k * stride..k * stride + expert_bytes].copy_from_slice(weights); +impl<'a> TimeRun<'a> { + fn prepare(args: &'a [String]) -> Result { + let t = parse_time_args(args)?; + let wall0 = mono_ns(); + let start = pin_and_probe(&t)?; + let loaded = load_case(&t)?; + let host = host_info()?; + let plan = plan_stream(&t, loaded.expert_bytes())?; + Ok(Self { args, t, wall0, start, loaded, host, plan }) } - let res_copies: Vec<&[u8]> = vec![resident.slice(expert_bytes)]; - let stm_all = streamed.slice(stride * copies_k); - let stm_copies: Vec<&[u8]> = (0..copies_k).map(|k| &stm_all[k * stride..k * stride + expert_bytes]).collect(); - let mut timed = Timed { + /// Writes the document by tmp + rename. + fn write_report(&self, end: &PinEnd, m: &Measured) -> Result<(), String> { + let j = doc::TimeDoc { run: self, end, m }.document(); + let t = &self.t; + let tmp = PathBuf::from(format!("{}.tmp", t.out.display())); + fs::write(&tmp, j.as_bytes()).map_err(|e| format!("{}: {e}", tmp.display()))?; + fs::rename(&tmp, &t.out).map_err(|e| format!("rename to {}: {e}", t.out.display())) + } + + /// Prints the summary line and maps the findings to the exit code. + fn finish(&self, m: &Measured) -> ExitCode { + let (t, tree, copies_k) = (&self.t, self.host.tree, self.plan.copies_k); + let (kept_res, kept_stm) = (m.regimes.kept_res, m.regimes.kept_stm); + println!( + "kernel_ab time: case={} tree={tree} pin={} slices={} resident_kept={kept_res} streamed_kept={kept_stm} \ + K={copies_k} out={}", + t.case, + t.pin, + t.slices, + t.out.display() + ); + if !m.regimes.all_ok { + eprintln!("kernel_ab time: a regime has no kept slice or a slice migrated off CPU {}", t.pin); + return ExitCode::from(3); + } + if !m.final_same { + eprintln!("kernel_ab time: the final output differs from the first call's"); + return ExitCode::from(4); + } + ExitCode::SUCCESS + } +} + +impl PinEnd { + fn read(run: &TimeRun) -> Self { + let threads = observed_threads(); + let sib1 = run.start.sibling.and_then(proc_stat_cpu); + let pin1 = proc_stat_cpu(run.t.pin); + Self { threads, sib1, pin1 } + } +} + +/// The aligned buffers of the run: the activations, the one resident expert copy and the K streamed copies. +struct Buffers { + tokens: Arena, + resident: Arena, + streamed: Arena, +} + +impl Buffers { + fn new(case: &CaseIn, plan: &StreamPlan) -> Self { + let header = case.header; + let weights = &case.blob[IN_HEADER..header.input_at()]; + let (expert_bytes, stride, all) = (weights.len(), plan.stride, plan.stride * plan.copies_k); + let mut tokens = Arena::::new(header.rows * H); + tokens.slice_mut(header.rows * H).copy_from_slice(&case.input()); + let mut resident = Arena::::new(stride); + resident.slice_mut(expert_bytes).copy_from_slice(weights); + let mut streamed = Arena::::new(all); + for k in 0..plan.copies_k { + streamed.slice_mut(all)[k * stride..k * stride + expert_bytes].copy_from_slice(weights); + } + Self { tokens, resident, streamed } + } +} + +/// The weight copies the timed calls cycle over, per regime. +struct CopySets<'a> { + resident: Vec<&'a [u8]>, + streamed: Vec<&'a [u8]>, + expert_bytes: usize, + plan: &'a StreamPlan, +} + +impl<'a> CopySets<'a> { + fn new(bufs: &'a Buffers, plan: &'a StreamPlan, expert_bytes: usize) -> Self { + let resident: Vec<&[u8]> = vec![bufs.resident.slice(expert_bytes)]; + let stm_all = bufs.streamed.slice(plan.stride * plan.copies_k); + let streamed: Vec<&[u8]> = + (0..plan.copies_k).map(|k| &stm_all[k * plan.stride..k * plan.stride + expert_bytes]).collect(); + Self { resident, streamed, expert_bytes, plan } + } + + /// The copies the selfcheck calls: the first resident one and the first and last streamed ones. + fn probes(&self) -> [&'a [u8]; 3] { + [self.resident[0], self.streamed[0], self.streamed[self.plan.copies_k - 1]] + } + + fn spec(&self, t: &TimeArgs, label: &'a str, copies: &[&'a [u8]], selfcheck: bool) -> RegimeSpec<'a> { + RegimeSpec { + label, + copies: copies.to_vec(), + expert_bytes: self.expert_bytes, + stride: self.plan.stride, + llc: &self.plan.llc, + slices: t.slices, + slice_ms: t.slice_ms, + pin: t.pin, + selfcheck, + } + } +} + +fn new_timed(pool: DirectCpuPool, header: InHeader, tokens: &[f32]) -> Result, String> { + Ok(Timed { pool, gu: gate_up_row(header.gu).ok_or("gate/up type")?.1, down: down_row(header.down).ok_or("down type")?.1, header, pairs: (0..header.rows).map(|r| (r, 0)).collect(), - tokens: tokens.slice(header.rows * H), + tokens, out: vec![0.0f32; header.rows * H], - }; - // selfcheck: the timed call's output on every aligned copy is bit-identical to the first (unaligned) call's + }) +} + +fn same_bits(out: &[f32], want_bits: &[u32]) -> bool { + out.iter().map(|v| v.to_bits()).eq(want_bits.iter().copied()) +} + +/// The timed call's output on every aligned copy is bit-identical to the first (unaligned) call's. +fn selfcheck(timed: &mut Timed, want_bits: &[u32], weights: [&[u8]; 3]) -> Result { let mut selfcheck = true; - for w in [res_copies[0], stm_copies[0], stm_copies[copies_k - 1]] { + for w in weights { timed.call(w)?; - selfcheck &= timed.out.iter().map(|v| v.to_bits()).eq(want_bits.iter().copied()); + selfcheck &= same_bits(&timed.out, want_bits); } if !selfcheck { return Err("selfcheck failed: the timed call differs from the first call".to_owned()); } + Ok(selfcheck) +} - let ghz0 = core_ghz(); - let mut regimes = Vec::new(); - let mut all_ok = true; - let (mut kept_res, mut kept_stm) = (0, 0); +fn run_regimes(t: &TimeArgs, timed: &mut Timed, sets: &CopySets, selfcheck: bool) -> Result { + let mut res = RegimeResults { json: Vec::new(), all_ok: true, kept_res: 0, kept_stm: 0 }; for (label, copies, sel) in - [("RESIDENT", &res_copies, RegimeSel::Resident), ("STREAMED", &stm_copies, RegimeSel::Streamed)] + [("RESIDENT", &sets.resident, RegimeSel::Resident), ("STREAMED", &sets.streamed, RegimeSel::Streamed)] { if t.regime != RegimeSel::Both && t.regime != sel { continue; } - let spec = RegimeSpec { - label, - copies: copies.clone(), - expert_bytes, - stride, - llc: &llc, - slices: t.slices, - slice_ms: t.slice_ms, - pin: t.pin, - selfcheck, - }; - let r = run_regime(&mut timed, &spec)?; - all_ok &= r.ok; + let r = run_regime(timed, &sets.spec(t, label, copies, selfcheck))?; + res.all_ok &= r.ok; if sel == RegimeSel::Resident { - kept_res = r.kept + res.kept_res = r.kept } else { - kept_stm = r.kept + res.kept_stm = r.kept } - regimes.push(r.json); + res.json.push(r.json); } + Ok(res) +} + +/// The selfcheck, the two calibrated regimes and the final unchanged-output check. +fn measure(run: &TimeRun, pool: DirectCpuPool, want: &[f32]) -> Result { + let (header, expert_bytes) = (run.loaded.case.header, run.loaded.expert_bytes()); + let want_bits: Vec = want.iter().map(|v| v.to_bits()).collect(); + let bufs = Buffers::new(&run.loaded.case, &run.plan); + let mut timed = new_timed(pool, header, bufs.tokens.slice(header.rows * H))?; + let sets = CopySets::new(&bufs, &run.plan, expert_bytes); + let selfcheck = selfcheck(&mut timed, &want_bits, sets.probes())?; + let ghz0 = core_ghz(); + let regimes = run_regimes(&run.t, &mut timed, &sets, selfcheck)?; let ghz1 = core_ghz(); - timed.call(res_copies[0])?; - let final_same = timed.out.iter().map(|v| v.to_bits()).eq(want_bits.iter().copied()); + timed.call(sets.resident[0])?; + let final_same = same_bits(&timed.out, &want_bits); + Ok(Measured { selfcheck, regimes, ghz: (ghz0, ghz1), final_same, output_sha: f32_bits_sha(want) }) +} - let threads = observed_threads(); - let sib1 = sibling.and_then(proc_stat_cpu); - let pin1 = proc_stat_cpu(t.pin); - let frac = |f: Option| f.map_or("null".to_owned(), |v| jnum(v, 4)); - let rust_fmt = |l: &str| jstr(l); - let (gu_name, down_name) = - (gate_up_row(header.gu).map_or("?", |x| x.4), down_row(header.down).map_or("?", |x| x.4)); - let in_name = format!("case-{}.in", t.case); - let command_line = format!( - "time --run-dir {} --case {} --slices {} --pin {} --out {}{}{}", - t.dir.display(), - t.case, - t.slices, - t.pin, - t.out.display(), - if args.iter().any(|a| a == "--slice-ms") { format!(" --slice-ms {}", t.slice_ms) } else { String::new() }, - match t.regime { - RegimeSel::Both => String::new(), - RegimeSel::Resident => " --regime resident".to_owned(), - RegimeSel::Streamed => " --regime streamed".to_owned(), - } - ); - let mut j = String::from( - "{\n \"format\": \"KAB1-time\",\n \"version\": 1,\n \"mode\": \"time\",\n \"writer\": \"rust\",\n", - ); - j += &format!( - " \"command_line\": {},\n \"run_dir\": {},\n \"manifest_sha256\": {},\n", - jstr(&command_line), - jstr(&t.dir.display().to_string()), - jstr(&manifest_sha) - ); - j += &format!( - " \"case\": {{\"id\": {}, \"gu_type\": {}, \"down_type\": {}, \"gu_name\": {}, \"down_name\": {}, \"rows\": \ - {}, \"input_file\": {}, \"input_sha256\": {}, \"input_sha256_matches_manifest\": true, \"expert_bytes\": \ - {}}},\n", - jstr(&t.case), - header.gu, - header.down, - jstr(gu_name), - jstr(down_name), - header.rows, - jstr(&in_name), - jstr(&entry.in_sha256), - expert_bytes - ); - j += &format!( - " \"tree\": {},\n \"tree_detail\": {{\"tree\": {}, \"cpu_report\": [{}], \"strata_env\": {}}},\n \ - \"effective_env\": {},\n", - jstr(tree), - jstr(tree), - report.iter().map(|l| rust_fmt(l)).collect::>().join(", "), - json_env(&env), - json_env(&env) - ); - j += &format!( - " \"pool\": {{\"workers\": 1, \"host_drains\": true, \"threads_observed\": [{}], \"note\": \ - \"DirectCpuPool::new(1): one worker thread plus the calling thread that drains beside it (pool.cpp \ - host_works_); both inherit the one-CPU mask of the pin\"}},\n", - threads - .iter() - .map(|(n, c)| format!( - "{{\"name\": {}, \"cpu\": {}}}", - jstr(n), - c.map_or("null".to_owned(), |c| c.to_string()) - )) - .collect::>() - .join(", ") - ); - j += &format!( - " \"pin\": {{\"cpu\": {}, \"thread_siblings_list\": {}, \"sibling_cpu\": {}, \"physical_core_id\": {}, \ - \"pin_busy_fraction_during_run\": {}, \"sibling_busy_fraction_during_run\": {}, \"sibling_busy_note\": \ - \"/proc/stat jiffies of the sibling logical CPU between the start and the end of this process; it is recorded, \ - no threshold is applied here\", \"scaling_governor\": {}, \"cpufreq_boost\": {}, \"loadavg_start\": {}, \ - \"loadavg_end\": {}, \"final_cpu\": {}}},\n", - t.pin, - jstr(&sib_text), - sibling.map_or("null".to_owned(), |s| s.to_string()), - jstr(&read_text(&format!("{cpu_dir}/topology/core_id"))), - frac(busy_fraction(pin0, pin1)), - if sibling.is_some() { frac(busy_fraction(sib0, sib1)) } else { "null".to_owned() }, - jstr(&read_text(&format!("{cpu_dir}/cpufreq/scaling_governor"))), - jstr(&read_text("/sys/devices/system/cpu/cpufreq/boost")), - jstr(&load0), - jstr(&read_text("/proc/loadavg")), - current_cpu().map_or("null".to_owned(), |c| c.to_string()) - ); - j += &format!( - " \"buffers\": {{\"alignment_bytes\": {ALIGN}, \"expert_copy_stride_bytes\": {stride}, \ - \"activations_aligned\": true, \"scratch_aligned\": false, \"scratch_note\": \"the pool's own scratch is \ - allocated inside the crate\"}},\n" - ); - j += &format!( - " \"clock_calibration\": {{\"method\": {}, \"source\": \"engine/strata/src/kernels/cpu/tq_cpu_parity.cpp \ - --bench: core_ghz() lines 273-284, time_slice() lines 290-304; the dependent-add chain needs inline assembly, \ - so the safe Rust twin chains multiplies\", \"drop_rule\": {{\"source_file\": \ - \"engine/strata/src/kernels/cpu/tq_cpu_parity.cpp\", \"source_line\": 303, \"source_text\": \"std::fabs(g1 - \ - g0) > 0.05 * g0\", \"fraction\": {}, \"meaning\": \"a slice whose calibrated clock moved by more than 5 \ - percent between its before and after calibration is dropped\"}}, \"slice_ms_source\": \"tq_cpu_parity.cpp:461 \ - slice_ms = quick ? 40 : 60\", \"ghz_at_start\": {}, \"ghz_at_end\": {}, \"tsc_invariant\": null, \"clocks\": \ - \"monotonic ns (std::time::Instant); no TSC read: rdtsc and lfence are unsafe intrinsics and the crate keeps \ - unsafe_code = deny\"}},\n", - jstr(CLOCK_METHOD), - jnum(CLOCK_MOVED_FRACTION, 2), - jnum(ghz0, 6), - jnum(ghz1, 6) - ); - j += &format!( - " \"build\": {{\"profile\": {}, \"rustflags\": {}, \"example\": \ - \"crates/native-cpu-expert/examples/kernel_ab.rs\"}},\n", - jstr(if cfg!(debug_assertions) { "dev" } else { "release" }), - jstr(&std::env::var("RUSTFLAGS").unwrap_or_default()) - ); - j += &format!( - " \"selfcheck_bitwise_equal_first_call\": {selfcheck},\n \"final_output_unchanged\": {final_same},\n \ - \"output_sha256\": {},\n \"duration_ns\": {},\n \"timing_caveat\": \"numbers from a shared host are not \ - evidence by themselves; loadavg and the sibling busy fraction are recorded above\",\n \"regimes\": [\n \ - {}\n ]\n}}\n", - jstr(&output_sha), - mono_ns() - wall0, - regimes.join(",\n ") - ); - let tmp = PathBuf::from(format!("{}.tmp", t.out.display())); - fs::write(&tmp, j.as_bytes()).map_err(|e| format!("{}: {e}", tmp.display()))?; - fs::rename(&tmp, &t.out).map_err(|e| format!("rename to {}: {e}", t.out.display()))?; - println!( - "kernel_ab time: case={} tree={tree} pin={} slices={} resident_kept={kept_res} streamed_kept={kept_stm} \ - K={copies_k} out={}", - t.case, - t.pin, - t.slices, - t.out.display() - ); - if !all_ok { - eprintln!("kernel_ab time: a regime has no kept slice or a slice migrated off CPU {}", t.pin); - return Ok(ExitCode::from(3)); - } - if !final_same { - eprintln!("kernel_ab time: the final output differs from the first call's"); - return Ok(ExitCode::from(4)); - } - Ok(ExitCode::SUCCESS) +/// `kernel_ab time ...`: one fresh process, one case, the resident and the streamed regime, JSON written by tmp + +/// rename. +/// Exit codes as `kab time`: 0 ok; 1 usage / refused input; 3 a regime kept no slice or a slice migrated off the pin; 4 +/// the final output differs. +pub(super) fn cmd_time(args: &[String]) -> Result { + let run = TimeRun::prepare(args)?; + // the pool is created AFTER the pin: its worker inherits the one-CPU mask (rust_platform::cores sees a one-CPU + // affinity) + let mut pool = DirectCpuPool::new(1).map_err(|e| format!("DirectCpuPool::new(1) failed: {e:?}"))?; + let want = compute_case(&mut pool, &run.loaded.case)?; + let m = measure(&run, pool, &want)?; + let end = PinEnd::read(&run); + run.write_report(&end, &m)?; + Ok(run.finish(&m)) } diff --git a/crates/native-cpu-expert/examples/kernel_ab/cmd_time_fn/doc.rs b/crates/native-cpu-expert/examples/kernel_ab/cmd_time_fn/doc.rs new file mode 100644 index 00000000..2c8ee495 --- /dev/null +++ b/crates/native-cpu-expert/examples/kernel_ab/cmd_time_fn/doc.rs @@ -0,0 +1,190 @@ +//! The KAB1-time JSON document of `kernel_ab time`, assembled in ten consecutive sections. + +#[allow(unused_imports)] +use super::*; + +/// The three inputs of the document besides the run itself: the pin facts after the run and the measurements. +pub(super) struct TimeDoc<'a> { + pub(super) run: &'a TimeRun<'a>, + pub(super) end: &'a PinEnd, + pub(super) m: &'a Measured, +} + +fn frac(f: Option) -> String { + f.map_or("null".to_owned(), |v| jnum(v, 4)) +} + +impl TimeDoc<'_> { + /// The whole document: the sections follow each other in the order of the file. + pub(super) fn document(&self) -> String { + [ + String::from( + "{\n \"format\": \"KAB1-time\",\n \"version\": 1,\n \"mode\": \"time\",\n \"writer\": \"rust\",\n", + ), + self.run_info(), + self.case_json(), + self.tree_json(), + self.pool_json(), + self.pin_json(), + self.buffers_json(), + self.clock_json(), + self.build_json(), + self.tail_json(), + ] + .concat() + } + + /// The command line as `kab time` would have been given it. + fn command_line(&self) -> String { + let (t, args) = (&self.run.t, self.run.args); + format!( + "time --run-dir {} --case {} --slices {} --pin {} --out {}{}{}", + t.dir.display(), + t.case, + t.slices, + t.pin, + t.out.display(), + if args.iter().any(|a| a == "--slice-ms") { format!(" --slice-ms {}", t.slice_ms) } else { String::new() }, + match t.regime { + RegimeSel::Both => String::new(), + RegimeSel::Resident => " --regime resident".to_owned(), + RegimeSel::Streamed => " --regime streamed".to_owned(), + } + ) + } + + fn run_info(&self) -> String { + let t = &self.run.t; + format!( + " \"command_line\": {},\n \"run_dir\": {},\n \"manifest_sha256\": {},\n", + jstr(&self.command_line()), + jstr(&t.dir.display().to_string()), + jstr(&self.run.loaded.manifest_sha) + ) + } + + fn case_json(&self) -> String { + let (t, loaded) = (&self.run.t, &self.run.loaded); + let header = loaded.case.header; + let (gu_name, down_name) = + (gate_up_row(header.gu).map_or("?", |x| x.4), down_row(header.down).map_or("?", |x| x.4)); + let in_name = format!("case-{}.in", t.case); + format!( + " \"case\": {{\"id\": {}, \"gu_type\": {}, \"down_type\": {}, \"gu_name\": {}, \"down_name\": {}, \ + \"rows\": {}, \"input_file\": {}, \"input_sha256\": {}, \"input_sha256_matches_manifest\": true, \ + \"expert_bytes\": {}}},\n", + jstr(&t.case), + header.gu, + header.down, + jstr(gu_name), + jstr(down_name), + header.rows, + jstr(&in_name), + jstr(&loaded.entry.in_sha256), + loaded.expert_bytes() + ) + } + + fn tree_json(&self) -> String { + let host = &self.run.host; + format!( + " \"tree\": {},\n \"tree_detail\": {{\"tree\": {}, \"cpu_report\": [{}], \"strata_env\": {}}},\n \ + \"effective_env\": {},\n", + jstr(host.tree), + jstr(host.tree), + host.report.iter().map(|l| jstr(l)).collect::>().join(", "), + json_env(&host.env), + json_env(&host.env) + ) + } + + fn pool_json(&self) -> String { + format!( + " \"pool\": {{\"workers\": 1, \"host_drains\": true, \"threads_observed\": [{}], \"note\": \ + \"DirectCpuPool::new(1): one worker thread plus the calling thread that drains beside it (pool.cpp \ + host_works_); both inherit the one-CPU mask of the pin\"}},\n", + self.end + .threads + .iter() + .map(|(n, c)| format!( + "{{\"name\": {}, \"cpu\": {}}}", + jstr(n), + c.map_or("null".to_owned(), |c| c.to_string()) + )) + .collect::>() + .join(", ") + ) + } + + fn pin_json(&self) -> String { + let (start, end) = (&self.run.start, self.end); + let (cpu_dir, sibling) = (&start.cpu_dir, start.sibling); + format!( + " \"pin\": {{\"cpu\": {}, \"thread_siblings_list\": {}, \"sibling_cpu\": {}, \"physical_core_id\": {}, \ + \"pin_busy_fraction_during_run\": {}, \"sibling_busy_fraction_during_run\": {}, \"sibling_busy_note\": \ + \"/proc/stat jiffies of the sibling logical CPU between the start and the end of this process; it is \ + recorded, no threshold is applied here\", \"scaling_governor\": {}, \"cpufreq_boost\": {}, \ + \"loadavg_start\": {}, \"loadavg_end\": {}, \"final_cpu\": {}}},\n", + self.run.t.pin, + jstr(&start.sib_text), + sibling.map_or("null".to_owned(), |s| s.to_string()), + jstr(&read_text(&format!("{cpu_dir}/topology/core_id"))), + frac(busy_fraction(start.pin0, end.pin1)), + if sibling.is_some() { frac(busy_fraction(start.sib0, end.sib1)) } else { "null".to_owned() }, + jstr(&read_text(&format!("{cpu_dir}/cpufreq/scaling_governor"))), + jstr(&read_text("/sys/devices/system/cpu/cpufreq/boost")), + jstr(&start.load0), + jstr(&read_text("/proc/loadavg")), + current_cpu().map_or("null".to_owned(), |c| c.to_string()) + ) + } + + fn buffers_json(&self) -> String { + let stride = self.run.plan.stride; + format!( + " \"buffers\": {{\"alignment_bytes\": {ALIGN}, \"expert_copy_stride_bytes\": {stride}, \ + \"activations_aligned\": true, \"scratch_aligned\": false, \"scratch_note\": \"the pool's own scratch is \ + allocated inside the crate\"}},\n" + ) + } + + fn clock_json(&self) -> String { + format!( + " \"clock_calibration\": {{\"method\": {}, \"source\": \"engine/strata/src/kernels/cpu/tq_cpu_parity.cpp \ + --bench: core_ghz() lines 273-284, time_slice() lines 290-304; the dependent-add chain needs inline \ + assembly, so the safe Rust twin chains multiplies\", \"drop_rule\": {{\"source_file\": \ + \"engine/strata/src/kernels/cpu/tq_cpu_parity.cpp\", \"source_line\": 303, \"source_text\": \"std::fabs(g1 \ + - g0) > 0.05 * g0\", \"fraction\": {}, \"meaning\": \"a slice whose calibrated clock moved by more than 5 \ + percent between its before and after calibration is dropped\"}}, \"slice_ms_source\": \ + \"tq_cpu_parity.cpp:461 slice_ms = quick ? 40 : 60\", \"ghz_at_start\": {}, \"ghz_at_end\": {}, \ + \"tsc_invariant\": null, \"clocks\": \"monotonic ns (std::time::Instant); no TSC read: rdtsc and lfence \ + are unsafe intrinsics and the crate keeps unsafe_code = deny\"}},\n", + jstr(CLOCK_METHOD), + jnum(CLOCK_MOVED_FRACTION, 2), + jnum(self.m.ghz.0, 6), + jnum(self.m.ghz.1, 6) + ) + } + + fn build_json(&self) -> String { + format!( + " \"build\": {{\"profile\": {}, \"rustflags\": {}, \"example\": \ + \"crates/native-cpu-expert/examples/kernel_ab.rs\"}},\n", + jstr(if cfg!(debug_assertions) { "dev" } else { "release" }), + jstr(&std::env::var("RUSTFLAGS").unwrap_or_default()) + ) + } + + fn tail_json(&self) -> String { + let (selfcheck, final_same) = (self.m.selfcheck, self.m.final_same); + format!( + " \"selfcheck_bitwise_equal_first_call\": {selfcheck},\n \"final_output_unchanged\": {final_same},\n \ + \"output_sha256\": {},\n \"duration_ns\": {},\n \"timing_caveat\": \"numbers from a shared host are not \ + evidence by themselves; loadavg and the sibling busy fraction are recorded above\",\n \"regimes\": [\n \ + {}\n ]\n}}\n", + jstr(&self.m.output_sha), + mono_ns() - self.run.wall0, + self.m.regimes.json.join(",\n ") + ) + } +} diff --git a/crates/native-cpu-expert/examples/kernel_ab/round_records_fn.rs b/crates/native-cpu-expert/examples/kernel_ab/round_records_fn.rs index e62d41f7..80cc806a 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 @@ -174,13 +174,24 @@ 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)?; +/// The counts of the `alternate` command line, range checked: rounds, batch, the case id and the slices per regime. +struct AltCounts { + rounds: u32, + batch: u32, + case: String, + slices: usize, +} + +fn alt_rounds_batch(f: &Flags) -> Result<(u32, u32), String> { let rounds = f.number::("rounds")?.ok_or("--rounds is required")?; let batch = f.number::("batch")?.ok_or("--batch is required")?; if !(1..=10_000).contains(&rounds) || !(1..=1000).contains(&batch) { return Err("--rounds must be 1..10000 and --batch 1..1000 (the batch number, counted from 1)".to_owned()); } + Ok((rounds, batch)) +} + +fn alt_case_slices(f: &Flags) -> Result<(String, usize), String> { let case = f.req("case")?.to_owned(); if !valid_id(&case) { return Err(format!("--case {case:?} is not a plain identifier")); @@ -189,16 +200,28 @@ pub(super) fn parse_alt_args(args: &[String]) -> Result { if !(1..=100_000).contains(&slices) { return Err("--slices must be 1..100000".to_owned()); } + Ok((case, slices)) +} + +fn alt_counts(f: &Flags) -> Result { + let (rounds, batch) = alt_rounds_batch(f)?; + let (case, slices) = alt_case_slices(f)?; + Ok(AltCounts { rounds, batch, case, slices }) +} + +pub(super) fn parse_alt_args(args: &[String]) -> Result { + let f = Flags::parse(args, &ALT_FLAGS)?; + let c = alt_counts(&f)?; Ok(AltArgs { dir: PathBuf::from(f.req("run-dir")?), - case, - rounds, - batch, + case: c.case, + rounds: c.rounds, + batch: c.batch, pin: f.number::("pin")?.ok_or("--pin is required")?, schedule: PathBuf::from(f.req("schedule")?), seed: f.number::("seed")?.unwrap_or(1), out: f.get("out").map(PathBuf::from), - slices, + slices: c.slices, slice_ms: f.number::("slice-ms")?, llc_bytes: f.number::("llc-bytes")?, machine_role: f.get("machine-role").map(str::to_owned), diff --git a/crates/native-cpu-expert/examples/kernel_ab/run_regime_fn.rs b/crates/native-cpu-expert/examples/kernel_ab/run_regime_fn.rs index 8fb62e68..bca34167 100644 --- a/crates/native-cpu-expert/examples/kernel_ab/run_regime_fn.rs +++ b/crates/native-cpu-expert/examples/kernel_ab/run_regime_fn.rs @@ -3,20 +3,71 @@ #[allow(unused_imports)] use super::*; -pub(super) fn run_regime(t: &mut Timed, spec: &RegimeSpec) -> Result { - let mut next = 0usize; - // warm-up (not recorded): tables and buffers, and for STREAMED one full pass over the copies so every page is - // resident +/// The warm-up (not recorded): tables and buffers, and for STREAMED one full pass over the copies so every page is +/// resident. +fn warm_up(t: &mut Timed, spec: &RegimeSpec, next: &mut usize) -> Result<(), String> { for _ in 0..3 { - t.call(spec.copies[next % spec.copies.len()])?; - next += 1; + t.call(spec.copies[*next % spec.copies.len()])?; + *next += 1; } if spec.copies.len() > 1 { for _ in 0..spec.copies.len() { - t.call(spec.copies[next % spec.copies.len()])?; - next += 1; + t.call(spec.copies[*next % spec.copies.len()])?; + *next += 1; } } + Ok(()) +} + +/// The statistics object of a regime up to its medians (no trailing comma). +fn regime_head(spec: &RegimeSpec, counts: (usize, usize), migrated: Option, meds: (String, String)) -> String { + format!( + "{{\"regime\": {}, \"copies_k\": {}, \"expert_bytes\": {}, \"copy_stride_bytes\": {}, \"working_set_bytes\": \ + {}, \"llc_level\": {}, \"llc_bytes\": {}, \"llc_source\": {}, \"working_set_over_llc\": {}, \"slice_ms\": {}, \ + \"slices_requested\": {}, \"slices_kept\": {}, \"dropped_count\": {}, \"selfcheck_bitwise_equal_first_call\": \ + {}, \"migrated_slices\": {}, \"median_ns_per_call\": {}, \"median_cycles_per_call\": {}", + jstr(spec.label), + spec.copies.len(), + spec.expert_bytes, + spec.stride, + spec.expert_bytes * spec.copies.len(), + spec.llc.level, + spec.llc.bytes, + jstr(&spec.llc.source), + spec.copies.len() > 1, + jnum(spec.slice_ms, 1), + spec.slices, + counts.0, + counts.1, + spec.selfcheck, + migrated.map_or("null".to_owned(), |m| m.to_string()), + meds.0, + meds.1 + ) +} + +/// The JSON of a regime: the statistics and the kept and the dropped slices. +fn regime_json( + spec: &RegimeSpec, + kept: &[(usize, Slice)], + dropped: &[(usize, Slice)], + migrated: Option, +) -> String { + let ns: Vec = kept.iter().map(|k| k.1.ns_per_call).collect(); + let cyc: Vec = kept.iter().map(|k| k.1.cycles_per_call).collect(); + let med = |v: &[f64], d: usize| if v.is_empty() { "null".to_owned() } else { jnum(median_of(v), d) }; + let list = |v: &[(usize, Slice)]| v.iter().map(|(i, s)| slice_json(s, *i)).collect::>().join(",\n "); + let head = regime_head(spec, (kept.len(), dropped.len()), migrated, (med(&ns, 3), med(&cyc, 1))); + format!( + "{head},\n \"slices\": [\n {}],\n \"dropped\": [\n {}]}}", + list(kept), + list(dropped) + ) +} + +pub(super) fn run_regime(t: &mut Timed, spec: &RegimeSpec) -> Result { + let mut next = 0usize; + warm_up(t, spec, &mut next)?; let (mut kept, mut dropped): (Numbered, Numbered) = (Vec::new(), Vec::new()); let mut migrated: Option = cfg!(target_os = "linux").then_some(0); for i in 0..spec.slices { @@ -29,36 +80,7 @@ pub(super) fn run_regime(t: &mut Timed, spec: &RegimeSpec) -> Result = kept.iter().map(|k| k.1.ns_per_call).collect(); - let cyc: Vec = kept.iter().map(|k| k.1.cycles_per_call).collect(); - let med = |v: &[f64], d: usize| if v.is_empty() { "null".to_owned() } else { jnum(median_of(v), d) }; - let list = |v: &[(usize, Slice)]| v.iter().map(|(i, s)| slice_json(s, *i)).collect::>().join(",\n "); - let json = format!( - "{{\"regime\": {}, \"copies_k\": {}, \"expert_bytes\": {}, \"copy_stride_bytes\": {}, \"working_set_bytes\": \ - {}, \"llc_level\": {}, \"llc_bytes\": {}, \"llc_source\": {}, \"working_set_over_llc\": {}, \"slice_ms\": {}, \ - \"slices_requested\": {}, \"slices_kept\": {}, \"dropped_count\": {}, \"selfcheck_bitwise_equal_first_call\": \ - {}, \"migrated_slices\": {}, \"median_ns_per_call\": {}, \"median_cycles_per_call\": {},\n \"slices\": \ - [\n {}],\n \"dropped\": [\n {}]}}", - jstr(spec.label), - spec.copies.len(), - spec.expert_bytes, - spec.stride, - spec.expert_bytes * spec.copies.len(), - spec.llc.level, - spec.llc.bytes, - jstr(&spec.llc.source), - spec.copies.len() > 1, - jnum(spec.slice_ms, 1), - spec.slices, - kept.len(), - dropped.len(), - spec.selfcheck, - migrated.map_or("null".to_owned(), |m| m.to_string()), - med(&ns, 3), - med(&cyc, 1), - list(&kept), - list(&dropped) - ); + let json = regime_json(spec, &kept, &dropped, migrated); Ok(RegimeRun { json, kept: kept.len(), ok: !kept.is_empty() && migrated.is_none_or(|m| m == 0) }) }