Files

245 lines
10 KiB
Rust

//! Functions: `write_out`, `compute_case`, `family_of`, `pin_or_warn` and 14 more.
//! Split out of `kernel_ab` to keep its files under the line limit.
#[allow(unused_imports)]
use super::*;
// ---------------------------------------------------------------------------- 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;
let mut b = Vec::with_capacity(OUT_HEADER + values.len() * 4);
for w in [OUT_MAGIC, 1, rows as u32, H as u32, tree_id] {
b.extend_from_slice(&w.to_le_bytes());
}
for v in values {
b.extend_from_slice(&v.to_bits().to_le_bytes());
}
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).
pub(super) fn compute_case(pool: &mut DirectCpuPool, case: &CaseIn) -> Result<Vec<f32>, 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);
let input = case.input();
PreparedJob::new(
ExpertFormats { gu, down },
ExpertBytes { gate: case.gate().into(), up: case.up().into(), down: case.down().into() },
input.clone().into(),
case.header.rows,
)
.map_err(|e| format!("PreparedJob refused the input: {e:?}"))?;
let pairs: Vec<(usize, usize)> = (0..case.header.rows).map(|t| (t, 0)).collect();
let expert = BorrowedExpert { gate: case.gate(), up: case.up(), down: case.down(), pairs: &pairs };
let experts = [expert];
let group = BorrowedGroup { tokens: &input, experts: &experts, stride: 1 };
let mut out = vec![0.0f32; case.header.rows * H];
pool.compute_group(gu, down, &group, &mut out).map_err(|e| format!("compute_group failed: {e:?}"))?;
Ok(out)
}
pub(super) fn family_of(report: &[String]) -> Option<&'static str> {
report
.iter()
.find(|l| l.starts_with("cpu: process kernel family "))
.map(|l| if l.starts_with("cpu: process kernel family AVX-512") { "avx512" } else { "avx2" })
}
/// Pins the calling thread; a refused pin only warns (the run goes on unpinned).
fn pin_or_warn(pin: usize) {
let previous = rust_topology::pin_current_thread(pin as i32);
if previous < 0 {
eprintln!("kernel_ab: the pin to CPU {pin} was refused; running unpinned");
}
}
/// Prints the kernel report of this process (one `REPORT` line each) and returns it.
fn print_kernel_report() -> Vec<String> {
let report = cpu_kernel_report();
for line in &report {
println!("REPORT {line}");
}
report
}
/// Our output of every selected case of the run directory, written below `target = (tree, out)`; returns the count.
fn run_tree_cases(
verified: &Verified,
pool: &mut DirectCpuPool,
target: (&str, &Path),
only_case: Option<&str>,
) -> Result<usize, String> {
let (tree, out) = target;
let mut done = 0usize;
for c in verified.cases.iter().filter(|c| only_case.is_none_or(|id| c.id == id)) {
let case = read_case_in(&verified.dir, c).map_err(|e| e.to_string())?;
let values = compute_case(pool, &case).map_err(|e| format!("case {}: {e}", c.id))?;
write_out(&out.join(format!("case-{}.rust-{tree}.out", c.id)), c.rows, tree, &values)?;
done += 1;
}
Ok(done)
}
pub(super) fn cmd_run_tree(
dir: &Path,
tree: &str,
out: &Path,
pin: usize,
only_case: Option<&str>,
) -> Result<ExitCode, String> {
let verified = verify_dir(dir).map_err(|e| e.to_string())?;
pin_or_warn(pin);
let report = print_kernel_report();
let family = family_of(&report).ok_or("no process kernel family line in cpu_kernel_report")?;
if family != tree {
eprintln!("kernel_ab: this process runs the {family} family, not {tree}");
return Ok(ExitCode::from(3));
}
fs::create_dir_all(out).map_err(|e| format!("{}: {e}", out.display()))?;
let mut pool = DirectCpuPool::new(1).map_err(|e| format!("DirectCpuPool::new(1) failed: {e:?}"))?;
let done = run_tree_cases(&verified, &mut pool, (tree, out), only_case)?;
if done == 0 {
return Err(format!("case {} is not in the manifest", only_case.unwrap_or("?")));
}
println!("RUN-TREE {tree} cases={done}");
Ok(ExitCode::SUCCESS)
}
// ------------------------------------------------------------------------------------------------ compare driver
/// The logical CPUs that share a core with `cpu` (from sysfs); None when the list cannot be read or parsed.
fn smt_siblings(cpu: usize) -> Option<Vec<usize>> {
let list = fs::read_to_string(format!("/sys/devices/system/cpu/cpu{cpu}/topology/thread_siblings_list")).ok()?;
let mut siblings = Vec::new();
for part in list.trim().split(',') {
let (a, b) = part.split_once('-').unwrap_or((part, part));
let (Ok(a), Ok(b)) = (a.trim().parse::<usize>(), b.trim().parse::<usize>()) else { return None };
siblings.extend((a..=b).filter(|s| *s != cpu));
}
Some(siblings)
}
/// (total, idle) jiffies of one logical CPU from /proc/stat.
fn cpu_jiffies(cpu: usize) -> Option<(u64, u64)> {
let stat = fs::read_to_string("/proc/stat").ok()?;
let line = stat.lines().find(|l| l.starts_with(&format!("cpu{cpu} ")))?;
let f: Vec<u64> = line.split_whitespace().skip(1).filter_map(|x| x.parse().ok()).collect();
let idle = f.get(3)? + f.get(4).copied().unwrap_or(0);
Some((f.iter().sum(), idle))
}
/// Below 5 percent busy between two samples; a missing sample or no elapsed time is not idle.
fn mostly_idle(before: Option<(u64, u64)>, after: Option<(u64, u64)>) -> bool {
match (before, after) {
(Some(b), Some(a)) => {
let total = a.0.saturating_sub(b.0);
let idle = a.1.saturating_sub(b.1);
total > 0 && (total - idle.min(total)) * 20 < total
}
_ => false,
}
}
/// Linux: is the SMT sibling of `cpu` idle (below 5 percent busy over 200 ms)? No sibling counts as idle. Elsewhere:
/// false (unknown).
pub(super) fn sibling_idle(cpu: usize) -> bool {
if !cfg!(target_os = "linux") {
return false;
}
let Some(siblings) = smt_siblings(cpu) else { return false };
if siblings.is_empty() {
return true;
}
let before: Vec<_> = siblings.iter().map(|s| cpu_jiffies(*s)).collect();
std::thread::sleep(std::time::Duration::from_millis(200));
siblings.iter().zip(before).all(|(s, b)| mostly_idle(b, cpu_jiffies(*s)))
}
pub(super) fn rustc_info() -> (String, String) {
// $RUSTC, then `rustc` on the PATH, then the rustup shim of the user (a non-login shell has no cargo bin directory
// on its PATH)
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];
let triple = if cfg!(windows) { "x86_64-pc-windows-msvc" } else { "x86_64-unknown-linux-gnu" };
let version = candidates
.iter()
.find_map(|rustc| {
Command::new(rustc)
.arg("--version")
.output()
.ok()
.filter(|o| o.status.success())
.and_then(|o| String::from_utf8(o.stdout).ok())
})
.map_or_else(|| "unknown (rustc not runnable at record time)".to_owned(), |s| s.trim().to_owned());
(version, triple.to_owned())
}
pub(super) fn host_os() -> String {
if cfg!(target_os = "linux")
&& let Ok(text) = fs::read_to_string("/etc/os-release")
&& let Some(l) = text.lines().find(|l| l.starts_with("PRETTY_NAME="))
{
return l["PRETTY_NAME=".len()..].trim_matches('"').to_owned();
}
std::env::consts::OS.to_owned()
}
pub(super) fn cpu_model_of(report: &[String]) -> String {
report
.iter()
.find(|l| l.starts_with("cpu: logical "))
.and_then(|l| l.split_once("): ").map(|x| x.1))
.and_then(|rest| rest.split(';').next())
.map_or_else(|| "unknown model".to_owned(), |s| s.trim().to_owned())
}
pub(super) fn parse_options(args: &[String]) -> Result<Options, String> {
let mut o = Options {
out: None,
pin: 0,
machine_role: None,
trees: TREES.iter().map(|t| (*t).to_owned()).collect(),
tree: None,
case: None,
};
let mut it = args.iter();
while let Some(a) = it.next() {
apply_option(&mut o, a.as_str(), &mut it)?;
}
if let Some(bad) = o.trees.iter().find(|t| !TREES.contains(&t.as_str())) {
return Err(format!("unknown tree {bad} (avx512 | avx2)"));
}
Ok(o)
}
/// The value after an option flag.
fn take_value(it: &mut std::slice::Iter<'_, String>, what: &str) -> Result<String, String> {
it.next().cloned().ok_or_else(|| format!("{what} needs a value"))
}
fn apply_option(o: &mut Options, flag: &str, it: &mut std::slice::Iter<'_, String>) -> Result<(), String> {
match flag {
"--out" => o.out = Some(PathBuf::from(take_value(it, "--out")?)),
"--pin" => {
o.pin = take_value(it, "--pin")?.parse().map_err(|_| "--pin takes a logical CPU number".to_owned())?
}
"--machine-role" => o.machine_role = Some(take_value(it, "--machine-role")?),
_ => return apply_tree_option(o, flag, it),
}
Ok(())
}
fn apply_tree_option(o: &mut Options, flag: &str, it: &mut std::slice::Iter<'_, String>) -> Result<(), String> {
match flag {
"--trees" => o.trees = take_value(it, "--trees")?.split(',').map(str::to_owned).collect(),
"--tree" => o.tree = Some(take_value(it, "--tree")?),
"--case" => o.case = Some(take_value(it, "--case")?),
other => return Err(format!("unknown option {other}")),
}
Ok(())
}