Files
leleka/crates/native-cpu-expert/examples/kernel_ab/impl_impl.rs
T

310 lines
10 KiB
Rust

//! 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::*;
impl Impl {
pub(super) fn name(self) -> &'static str {
match self {
Impl::Cpp => "cpp",
Impl::Rust => "rust",
}
}
}
impl Proc {
pub(super) fn name(&self) -> String {
format!("{}-{}-{}", self.imp.name(), self.tree, self.rep)
}
pub(super) fn parse(s: &str) -> Option<Proc> {
let mut p = s.split('-');
let imp = match p.next()? {
"cpp" => Impl::Cpp,
"rust" => Impl::Rust,
_ => return None,
};
let wanted = p.next()?;
let tree = *TREES.iter().find(|t| **t == wanted)?;
let rep = match p.next()? {
"a" => 'a',
"b" => 'b',
_ => return None,
};
p.next().is_none().then_some(Proc { imp, tree, rep })
}
}
/// Every process of a round for the given trees, in canonical order.
pub(super) fn procs_for(trees: &[&'static str]) -> Vec<Proc> {
let mut v = Vec::new();
for imp in [Impl::Cpp, Impl::Rust] {
for tree in trees {
for rep in ['a', 'b'] {
v.push(Proc { imp, tree, rep });
}
}
}
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).
pub(super) fn cell_env(p: &Proc) -> Vec<(String, String)> {
let mut v = Vec::new();
if p.tree == "avx2" {
v.push(("STRATA_FORCE_AVX2".to_owned(), "1".to_owned()));
}
if p.imp == Impl::Rust {
v.push(("LELEKA_CPU_POOL_PIN_HOST".to_owned(), "off".to_owned()));
v.push(("STRATA_POOL_SPIN_US".to_owned(), "0".to_owned()));
}
v.sort();
v
}
/// 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)],
cell: &[(String, String)],
) -> Command {
let mut c = Command::new(program);
c.env_clear();
for (k, v) in parent_env {
if !is_managed_name(&k.to_string_lossy()) {
c.env(k, v);
}
}
for (k, v) in cell {
c.env(k, v);
}
c
}
/// Runs a prepared cell command; a failure names the cell.
pub(super) fn run_cell(cmd: &mut Command, cell: &str) -> Result<std::process::Output, String> {
let out = cmd.output().map_err(|e| format!("cell {cell}: cannot start the process: {e}"))?;
if out.status.success() {
return Ok(out);
}
let tail = |b: &[u8]| {
String::from_utf8_lossy(b)
.lines()
.rev()
.take(3)
.collect::<Vec<_>>()
.into_iter()
.rev()
.collect::<Vec<_>>()
.join(" | ")
};
Err(format!(
"cell {cell} failed ({}): stderr: {}; stdout: {}",
out.status.code().map_or("killed by a signal".to_owned(), |c| format!("exit {c}")),
tail(&out.stderr),
tail(&out.stdout)
))
}
pub(super) fn splitmix(state: &mut u64) -> u64 {
*state = state.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = *state;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
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).
pub(super) fn make_schedule(seed: u64, batch: u32, rounds: u32, procs: &[Proc]) -> Vec<Vec<Proc>> {
let n = procs.len();
let mut out = Vec::new();
let mut base: Vec<Proc> = Vec::new();
for i in 0..rounds as usize {
if i % n == 0 {
let mut st = seed;
for x in [u64::from(batch), (i / n) as u64] {
st = st.wrapping_add(x.wrapping_mul(0x9E37_79B9_7F4A_7C15));
st = splitmix(&mut st);
}
base = procs.to_vec();
for j in (1..n).rev() {
let k = (splitmix(&mut st) % (j as u64 + 1)) as usize;
base.swap(j, k);
}
}
let mut order = base.clone();
order.rotate_left(i % n);
out.push(order);
}
out
}
pub(super) fn schedule_text(
seed: u64,
batch: u32,
rounds: u32,
case: &str,
pin: usize,
first_round: u32,
order: &[Vec<Proc>],
) -> 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"
);
for (i, o) in order.iter().enumerate() {
t += &format!("{}\t{}\n", first_round + i as u32, o.iter().map(Proc::name).collect::<Vec<_>>().join(","));
}
t
}
/// 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<Vec<(u32, Vec<Proc>)>, String> {
let mut lines = text.lines();
if !lines.next().is_some_and(|l| l.starts_with(SCHEDULE_MAGIC)) {
return Err("not a KAB1-alt schedule".to_owned());
}
let mut rounds: Vec<(u32, Vec<Proc>)> = Vec::new();
for l in lines.filter(|l| !l.starts_with('#') && !l.is_empty()) {
let (no, order) = parse_schedule_line(l)?;
if let Some(prev) = rounds.last()
&& !follows_round(prev, no, &order)
{
return Err(format!("round {no} does not follow round {} with the same processes", prev.0));
}
rounds.push((no, order));
}
if rounds.is_empty() {
return Err("the schedule has no round".to_owned());
}
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<Proc>), String> {
let (no, list) = l.split_once('\t').ok_or_else(|| format!("bad schedule line {l:?}"))?;
let no = no.parse::<u32>().map_err(|_| format!("bad round number in {l:?}"))?;
let order: Vec<Proc> = list
.split(',')
.map(|n| Proc::parse(n).ok_or_else(|| format!("unknown process {n:?} in the schedule")))
.collect::<Result<_, _>>()?;
Ok((no, order))
}
/// Whether round `no` with `order` is the round after `prev` and names the same processes.
fn follows_round(prev: &(u32, Vec<Proc>), 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<f64>,
cycles: Vec<f64>,
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<SliceSample, String> {
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<Samples, String> {
let mut samples = Samples { ns: Vec::new(), cycles: Vec::new(), max_drift: 0.0f64 };
for (key, keep) in [("slices", true), ("dropped", false)] {
for s in r.array(key)? {
let slice = parse_slice(s, keep)?;
samples.add_slice(&slice);
}
}
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<RegimeStat, String> {
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 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)"));
}
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<SetCounts, String> {
Ok(SetCounts {
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,
})
}