248 lines
12 KiB
Rust
248 lines
12 KiB
Rust
//! Moved out of the parent module by STRA-338: fn cmd_time.
|
|
|
|
#[allow(unused_imports)]
|
|
use super::*;
|
|
|
|
/// `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 t = parse_time_args(args)?;
|
|
let wall0 = mono_ns();
|
|
// pin first (before any buffer or pool exists, so the pool's threads inherit the mask), then the facts about the pin
|
|
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");
|
|
|
|
// the case: the KAB1 reader rule (validate, then use) and the manifest and case input hashes
|
|
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())?;
|
|
let header = case.header;
|
|
let weights = &case.blob[IN_HEADER..header.input_at()];
|
|
let expert_bytes = weights.len();
|
|
|
|
// environment and tree
|
|
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")?;
|
|
|
|
// 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)
|
|
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());
|
|
}
|
|
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());
|
|
}
|
|
|
|
// 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, &case)?;
|
|
let want_bits: Vec<u32> = want.iter().map(|v| v.to_bits()).collect();
|
|
let output_sha = f32_bits_sha(&want);
|
|
|
|
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(stride * copies_k);
|
|
for k in 0..copies_k {
|
|
streamed.slice_mut(stride * copies_k)[k * stride..k * stride + expert_bytes].copy_from_slice(weights);
|
|
}
|
|
let res_copies: Vec<&[u8]> = vec![resident.slice(expert_bytes)];
|
|
let stm_all = streamed.slice(stride * copies_k);
|
|
let stm_copies: Vec<&[u8]> = (0..copies_k).map(|k| &stm_all[k * stride..k * stride + expert_bytes]).collect();
|
|
|
|
let mut timed = 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: tokens.slice(header.rows * H),
|
|
out: vec![0.0f32; header.rows * H],
|
|
};
|
|
// selfcheck: the timed call's output on every aligned copy is bit-identical to the first (unaligned) call's
|
|
let mut selfcheck = true;
|
|
for w in [res_copies[0], stm_copies[0], stm_copies[copies_k - 1]] {
|
|
timed.call(w)?;
|
|
selfcheck &= timed.out.iter().map(|v| v.to_bits()).eq(want_bits.iter().copied());
|
|
}
|
|
if !selfcheck {
|
|
return Err("selfcheck failed: the timed call differs from the first call".to_owned());
|
|
}
|
|
|
|
let ghz0 = core_ghz();
|
|
let mut regimes = Vec::new();
|
|
let mut all_ok = true;
|
|
let (mut kept_res, mut kept_stm) = (0, 0);
|
|
for (label, copies, sel) in
|
|
[("RESIDENT", &res_copies, RegimeSel::Resident), ("STREAMED", &stm_copies, RegimeSel::Streamed)]
|
|
{
|
|
if t.regime != RegimeSel::Both && t.regime != sel {
|
|
continue;
|
|
}
|
|
let spec = RegimeSpec {
|
|
label,
|
|
copies: copies.clone(),
|
|
expert_bytes,
|
|
stride,
|
|
llc: &llc,
|
|
slices: t.slices,
|
|
slice_ms: t.slice_ms,
|
|
pin: t.pin,
|
|
selfcheck,
|
|
};
|
|
let r = run_regime(&mut timed, &spec)?;
|
|
all_ok &= r.ok;
|
|
if sel == RegimeSel::Resident {
|
|
kept_res = r.kept
|
|
} else {
|
|
kept_stm = r.kept
|
|
}
|
|
regimes.push(r.json);
|
|
}
|
|
let ghz1 = core_ghz();
|
|
timed.call(res_copies[0])?;
|
|
let final_same = timed.out.iter().map(|v| v.to_bits()).eq(want_bits.iter().copied());
|
|
|
|
let threads = observed_threads();
|
|
let sib1 = sibling.and_then(proc_stat_cpu);
|
|
let pin1 = proc_stat_cpu(t.pin);
|
|
let frac = |f: Option<f64>| f.map_or("null".to_owned(), |v| jnum(v, 4));
|
|
let rust_fmt = |l: &str| jstr(l);
|
|
let (gu_name, down_name) =
|
|
(gate_up_row(header.gu).map_or("?", |x| x.4), down_row(header.down).map_or("?", |x| x.4));
|
|
let in_name = format!("case-{}.in", t.case);
|
|
let command_line = format!(
|
|
"time --run-dir {} --case {} --slices {} --pin {} --out {}{}{}",
|
|
t.dir.display(),
|
|
t.case,
|
|
t.slices,
|
|
t.pin,
|
|
t.out.display(),
|
|
if args.iter().any(|a| a == "--slice-ms") { format!(" --slice-ms {}", t.slice_ms) } else { String::new() },
|
|
match t.regime {
|
|
RegimeSel::Both => String::new(),
|
|
RegimeSel::Resident => " --regime resident".to_owned(),
|
|
RegimeSel::Streamed => " --regime streamed".to_owned(),
|
|
}
|
|
);
|
|
let mut j = String::from(
|
|
"{\n \"format\": \"KAB1-time\",\n \"version\": 1,\n \"mode\": \"time\",\n \"writer\": \"rust\",\n",
|
|
);
|
|
j += &format!(
|
|
" \"command_line\": {},\n \"run_dir\": {},\n \"manifest_sha256\": {},\n",
|
|
jstr(&command_line),
|
|
jstr(&t.dir.display().to_string()),
|
|
jstr(&manifest_sha)
|
|
);
|
|
j += &format!(
|
|
" \"case\": {{\"id\": {}, \"gu_type\": {}, \"down_type\": {}, \"gu_name\": {}, \"down_name\": {}, \"rows\": {}, \"input_file\": {}, \"input_sha256\": {}, \"input_sha256_matches_manifest\": true, \"expert_bytes\": {}}},\n",
|
|
jstr(&t.case),
|
|
header.gu,
|
|
header.down,
|
|
jstr(gu_name),
|
|
jstr(down_name),
|
|
header.rows,
|
|
jstr(&in_name),
|
|
jstr(&entry.in_sha256),
|
|
expert_bytes
|
|
);
|
|
j += &format!(
|
|
" \"tree\": {},\n \"tree_detail\": {{\"tree\": {}, \"cpu_report\": [{}], \"strata_env\": {}}},\n \"effective_env\": {},\n",
|
|
jstr(tree),
|
|
jstr(tree),
|
|
report.iter().map(|l| rust_fmt(l)).collect::<Vec<_>>().join(", "),
|
|
json_env(&env),
|
|
json_env(&env)
|
|
);
|
|
j += &format!(
|
|
" \"pool\": {{\"workers\": 1, \"host_drains\": true, \"threads_observed\": [{}], \"note\": \"DirectCpuPool::new(1): one worker thread plus the calling thread that drains beside it (pool.cpp host_works_); both inherit the one-CPU mask of the pin\"}},\n",
|
|
threads
|
|
.iter()
|
|
.map(|(n, c)| format!(
|
|
"{{\"name\": {}, \"cpu\": {}}}",
|
|
jstr(n),
|
|
c.map_or("null".to_owned(), |c| c.to_string())
|
|
))
|
|
.collect::<Vec<_>>()
|
|
.join(", ")
|
|
);
|
|
j += &format!(
|
|
" \"pin\": {{\"cpu\": {}, \"thread_siblings_list\": {}, \"sibling_cpu\": {}, \"physical_core_id\": {}, \"pin_busy_fraction_during_run\": {}, \"sibling_busy_fraction_during_run\": {}, \"sibling_busy_note\": \"/proc/stat jiffies of the sibling logical CPU between the start and the end of this process; it is recorded, no threshold is applied here\", \"scaling_governor\": {}, \"cpufreq_boost\": {}, \"loadavg_start\": {}, \"loadavg_end\": {}, \"final_cpu\": {}}},\n",
|
|
t.pin,
|
|
jstr(&sib_text),
|
|
sibling.map_or("null".to_owned(), |s| s.to_string()),
|
|
jstr(&read_text(&format!("{cpu_dir}/topology/core_id"))),
|
|
frac(busy_fraction(pin0, pin1)),
|
|
if sibling.is_some() { frac(busy_fraction(sib0, sib1)) } else { "null".to_owned() },
|
|
jstr(&read_text(&format!("{cpu_dir}/cpufreq/scaling_governor"))),
|
|
jstr(&read_text("/sys/devices/system/cpu/cpufreq/boost")),
|
|
jstr(&load0),
|
|
jstr(&read_text("/proc/loadavg")),
|
|
current_cpu().map_or("null".to_owned(), |c| c.to_string())
|
|
);
|
|
j += &format!(
|
|
" \"buffers\": {{\"alignment_bytes\": {ALIGN}, \"expert_copy_stride_bytes\": {stride}, \"activations_aligned\": true, \"scratch_aligned\": false, \"scratch_note\": \"the pool's own scratch is allocated inside the crate\"}},\n"
|
|
);
|
|
j += &format!(
|
|
" \"clock_calibration\": {{\"method\": {}, \"source\": \"engine/strata/src/kernels/cpu/tq_cpu_parity.cpp --bench: core_ghz() lines 273-284, time_slice() lines 290-304; the dependent-add chain needs inline assembly, so the safe Rust twin chains multiplies\", \"drop_rule\": {{\"source_file\": \"engine/strata/src/kernels/cpu/tq_cpu_parity.cpp\", \"source_line\": 303, \"source_text\": \"std::fabs(g1 - g0) > 0.05 * g0\", \"fraction\": {}, \"meaning\": \"a slice whose calibrated clock moved by more than 5 percent between its before and after calibration is dropped\"}}, \"slice_ms_source\": \"tq_cpu_parity.cpp:461 slice_ms = quick ? 40 : 60\", \"ghz_at_start\": {}, \"ghz_at_end\": {}, \"tsc_invariant\": null, \"clocks\": \"monotonic ns (std::time::Instant); no TSC read: rdtsc and lfence are unsafe intrinsics and the crate keeps unsafe_code = deny\"}},\n",
|
|
jstr(CLOCK_METHOD),
|
|
jnum(CLOCK_MOVED_FRACTION, 2),
|
|
jnum(ghz0, 6),
|
|
jnum(ghz1, 6)
|
|
);
|
|
j += &format!(
|
|
" \"build\": {{\"profile\": {}, \"rustflags\": {}, \"example\": \"crates/native-cpu-expert/examples/kernel_ab.rs\"}},\n",
|
|
jstr(if cfg!(debug_assertions) { "dev" } else { "release" }),
|
|
jstr(&std::env::var("RUSTFLAGS").unwrap_or_default())
|
|
);
|
|
j += &format!(
|
|
" \"selfcheck_bitwise_equal_first_call\": {selfcheck},\n \"final_output_unchanged\": {final_same},\n \"output_sha256\": {},\n \"duration_ns\": {},\n \"timing_caveat\": \"numbers from a shared host are not evidence by themselves; loadavg and the sibling busy fraction are recorded above\",\n \"regimes\": [\n {}\n ]\n}}\n",
|
|
jstr(&output_sha),
|
|
mono_ns() - wall0,
|
|
regimes.join(",\n ")
|
|
);
|
|
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()))?;
|
|
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 !all_ok {
|
|
eprintln!("kernel_ab time: a regime has no kept slice or a slice migrated off CPU {}", t.pin);
|
|
return Ok(ExitCode::from(3));
|
|
}
|
|
if !final_same {
|
|
eprintln!("kernel_ab time: the final output differs from the first call's");
|
|
return Ok(ExitCode::from(4));
|
|
}
|
|
Ok(ExitCode::SUCCESS)
|
|
}
|