284 lines
10 KiB
Rust
284 lines
10 KiB
Rust
//! 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<usize>,
|
|
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<PinStart, String> {
|
|
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<String, String>,
|
|
pub(super) report: Vec<String>,
|
|
pub(super) tree: &'static str,
|
|
pub(super) plan: StreamPlan,
|
|
}
|
|
|
|
pub(super) fn prepare_time_run(args: &[String]) -> Result<Prepared, String> {
|
|
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<f32>), 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<usize>)>,
|
|
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<TimeCase, String> {
|
|
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<StreamPlan, String> {
|
|
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<Llc, String> {
|
|
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<f32>,
|
|
resident: Arena<u8>,
|
|
streamed: Arena<u8>,
|
|
}
|
|
|
|
pub(super) fn fill_buffers(case: &CaseIn, plan: &StreamPlan) -> TimeBuffers {
|
|
let rows = case.header.rows;
|
|
let weights = case.weights();
|
|
let mut tokens = Arena::<f32>::new(rows * H);
|
|
tokens.slice_mut(rows * H).copy_from_slice(&case.input());
|
|
let mut resident = Arena::<u8>::new(plan.stride);
|
|
resident.slice_mut(plan.expert_bytes).copy_from_slice(weights);
|
|
let mut streamed = Arena::<u8>::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<Timed<'a>, 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<String>,
|
|
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<Measured, String> {
|
|
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<bool, String> {
|
|
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<RegimeResults, String> {
|
|
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)
|
|
}
|