Files
leleka/crates/native-cpu-expert/examples/kernel_ab/cmd_time.rs
T
Pavlo RatushnyiandClaude Sonnet 5.5 b686f6ab75 STRA-338: rename the 854 mechanically named modules (impl_*, *_fn, *_<N>) after what they hold; mechanical_names census 854 -> 0
git mv of the files and of the module directories next to them, mod declarations, #[path] attributes and
the paths that name the modules, rewritten by scripts/dev/rename_mechanical.py from a reviewed name table.
Two files lost one to two lines so the 400-line limit holds again (qsa_prompt_index, original_verify_expert_probe).
limits-baseline.json: test fn_lines 0 -> 1 is --allow-increase for crates/deploy builtin_profiles.rs:149 (37 lines,
the speed-vs-strata session's file, not touched here); the prod params census falls 108 -> 1 (w_launch, extern C ABI).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 13:43:56 +01:00

340 lines
12 KiB
Rust

//! Moved out of the parent module by STRA-338: fn cmd_time.
#[allow(unused_imports)]
use super::*;
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<usize>,
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<usize>)>,
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<String, String>,
report: Vec<String>,
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<String>,
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<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 })
}
/// The case: the KAB1 reader rule (validate, then use) and the manifest and case input hashes.
fn load_case(t: &TimeArgs) -> Result<LoadedCase, 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 entry = entry.clone();
let case = read_case_in(&t.dir, &entry).map_err(|e| e.to_string())?;
Ok(LoadedCase { manifest_sha, entry, case })
}
/// The environment and the tree of this process.
fn host_info() -> Result<HostInfo, String> {
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 last-level cache of the pinned CPU: the override of `--llc-bytes`, else sysfs.
fn llc_for(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)
}
fn plan_stream(t: &TimeArgs, expert_bytes: usize) -> Result<StreamPlan, String> {
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 })
}
impl<'a> TimeRun<'a> {
fn prepare(args: &'a [String]) -> Result<Self, String> {
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 })
}
/// 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<f32>,
resident: Arena<u8>,
streamed: Arena<u8>,
}
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::<f32>::new(header.rows * H);
tokens.slice_mut(header.rows * H).copy_from_slice(&case.input());
let mut resident = Arena::<u8>::new(stride);
resident.slice_mut(expert_bytes).copy_from_slice(weights);
let mut streamed = Arena::<u8>::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<Timed<'_>, 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,
out: vec![0.0f32; header.rows * H],
})
}
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<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 run_regimes(t: &TimeArgs, timed: &mut Timed, sets: &CopySets, selfcheck: bool) -> Result<RegimeResults, String> {
let mut res = RegimeResults { json: Vec::new(), all_ok: true, kept_res: 0, kept_stm: 0 };
for (label, copies, sel) in
[("RESIDENT", &sets.resident, RegimeSel::Resident), ("STREAMED", &sets.streamed, RegimeSel::Streamed)]
{
if t.regime != RegimeSel::Both && t.regime != sel {
continue;
}
let r = run_regime(timed, &sets.spec(t, label, copies, selfcheck))?;
res.all_ok &= r.ok;
if sel == RegimeSel::Resident {
res.kept_res = r.kept
} else {
res.kept_stm = r.kept
}
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<Measured, String> {
let (header, expert_bytes) = (run.loaded.case.header, run.loaded.expert_bytes());
let want_bits: Vec<u32> = 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(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) })
}
/// `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<ExitCode, String> {
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))
}