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

275 lines
9.7 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
}
/// What the header line of a schedule file records about the batch.
#[derive(Clone, Copy)]
pub(super) struct ScheduleHeader<'a> {
pub(super) seed: u64,
pub(super) batch: u32,
pub(super) rounds: u32,
pub(super) case: &'a str,
pub(super) pin: usize,
}
pub(super) fn schedule_text(header: ScheduleHeader, first_round: u32, order: &[Vec<Proc>]) -> String {
let ScheduleHeader { seed, batch, rounds, case, pin } = header;
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()
&& !round_follows(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 comma-separated processes.
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))
}
/// Round `no` follows `prev`: the next number and the same set of processes.
fn round_follows(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 slice series of one regime: the kept slices' timings and the largest clock drift over kept and dropped slices.
struct SliceSeries {
ns: Vec<f64>,
cycles: Vec<f64>,
max_drift: f64,
}
fn read_slice(s: &Json, keep: bool, acc: &mut SliceSeries) -> Result<(), String> {
let (g0, g1) = (s.float("ghz_before")?, s.float("ghz_after")?);
if g0 > 0.0 {
acc.max_drift = acc.max_drift.max(((g1 - g0).abs() / g0).min(1.0));
}
if keep {
acc.ns.push(s.float("ns_per_call")?);
acc.cycles.push(s.float("cycles_per_call")?);
}
Ok(())
}
fn read_series(r: &Json) -> Result<SliceSeries, String> {
let mut acc = SliceSeries { ns: Vec::new(), cycles: Vec::new(), max_drift: 0.0f64 };
for (key, keep) in [("slices", true), ("dropped", false)] {
for s in r.array(key)? {
read_slice(s, keep, &mut acc)?;
}
}
Ok(acc)
}
pub(super) fn parse_regime(r: &Json, imp: Impl) -> Result<RegimeStat, String> {
let series = read_series(r)?;
let selfcheck_key =
if imp == Impl::Cpp { "selfcheck_bitwise_equal_compose_expert" } else { "selfcheck_bitwise_equal_first_call" };
let kept = r.uint("slices_kept")? as usize;
if kept != series.ns.len() || kept == 0 {
return Err(format!(
"slices_kept {kept} disagrees with the {} kept slices (or none was kept)",
series.ns.len()
));
}
regime_stat(r, series, selfcheck_key)
}
fn regime_stat(r: &Json, series: SliceSeries, selfcheck_key: &str) -> Result<RegimeStat, String> {
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: series.ns,
cycles: series.cycles,
max_drift: series.max_drift,
selfcheck: r.flag(selfcheck_key)?,
})
}